Returns the substring that appears the most frequently in a string.
Solutions
For example, the string "abababc" can appear at most AB consecutively, three times in a row. To distinguish it from the longest duplicate substring in a string, or the above string, the longest duplicate substring is abab. The solutions for the two questions are somewhat similar, and the data structure of the suffix array is used. Find the substring that appears the most frequently in a string. First, generate a suffix array. For example, the above string is:
abababcbababcababcbabcabcbcc
We can see that the first suffix array and the third suffix array start with AB, and the 5th suffix array is also AB. It can be seen that, if a string s appears before the suffix array I for the first time, if it repeats, the next appearance should be in the I + len (s) suffix array.
Implementation Code
# Include
# Include
# Include
# Include
# Include
Using namespace std; pair
Fun (const string & str) {vector
Subs; int len = str. size (); for (int I = 0; I <len; I ++) {subs. push_back (str. substr (I);} int count = 1; int maxCount = 1; string sub; for (int I = 0; I <len; I ++) {for (int j = I + 1; j <len; j ++) {count = 1; if (subs [I]. substr (0, j-I) = subs [j]. substr (0, j-I) {+ + count; // j-I is the length of the substring for (int k = j + j-I; k <len; k + = j-I) {if (subs [I]. substr (0, j-I) = subs [k]. substr (0, j-I) {+ + count;} else {break;} if (count> maxCount) {maxCount = count; sub = subs [I]. substr (0, j-I) ;}}return make_pair (maxCount, sub) ;}int main () {string str; pair
Rs; while (cin> str) {rs = fun (str); cout <
<<:<<<<:<<
Another idea:
Pair
Fun (const string & str) {vector
Subs; int len = str. size (); for (int I = 0; I <len; I ++) {subs. push_back (str. substr (I);} int count = 1; int maxCount = 1; string sub; // I is the length of the substring for (int I = 1; I <len; I ++) {for (int j = 0; j + I <len; j + = 1) {int k = j; count = 1; while (k + I <len & subs [k]. substr (0, I) = subs [k + I]. substr (0, I) {++ count; k + = I;} if (count> maxCount) {maxCount = count; sub = subs [j]. substr (0, I) ;}} return make_pair (maxCount, sub );}