For string X we can find the largest consecutive repeating substring in O (n ^ 2) using the Z-algorithm , which Given a string S of length n, the Z Algorithm produces an array Z where Z[i] is the length of the longest substring starting from pat[i] which is also a prefix of pat ( Source )
For each suffix X start with i using the Z algorithm for this substring:
int result = 0; for(int i = 0; i < X.length(); i++) int[]z = Z-algo(X.substring(i)); //this take O(n) for(int j = i + result + 1; j < X.length(); j++) if(z[j] >= j - i + 1) result = (j - i + 1);
Repeating the above procedure, until we can find any duplicate substring, we can get the algorithm O (n ^ 3).
Note : after re-reading the question, especially in the last example, I will find out that the actual repeating substrings are limited only to the original substrings. Thus, the time complexity can be reduced to O (n ^ 2 log n) using the maximum heap.
Pham trung
source share