Given a string str, find the longest repeating non-overlapping substring in it. In other words find 2 identical substrings of maximum length which do not overlap. If there exists more than one such substring return any of them.
classSolution {publicStringlongestRepeatedSubstring(String str) {int n =str.length();// dp[i][j] -> Length of longest repeating substring ending at i and jth indicesint dp[][] =newint[n +1][n +1];int res_length =0;int index =0;for (int i =1; i <= n; i++) {for (int j = i +1; j <= n; j++) {// If the characters at ith and jth indices are same// Then we need to check that there should be no overlap// This can be done by just checking is the distance// between i & j > the length of previous matching substring(dp[i-1][j-1])if (str.charAt(i -1) ==str.charAt(j -1) && dp[i -1][j -1] < (j - i)) { dp[i][j] = dp[i -1][j -1] +1;if (dp[i][j] > res_length) { res_length = dp[i][j]; index = i; } }// Default dp[i][j]->0 } }StringBuilder res =newStringBuilder();while (res_length >0)res.append(str.charAt(i--));returnres.reverse().toString(); }}