//字符串中连续出现次数最多的子串
//利用后缀数组后缀数组是一种数据结构,对一个字符串生成相应的后缀数组后,然后再排序,排完序依次检测相邻的两个字符串的开头公共部分。
//这样的时间复杂度为:总的时间复杂度是 O(N^2*logN),
//后缀数组,每一行比上一行少一个,跳行就可出现少2个、3个……
//第一趟:(一个长度的子串)第一行a与第二行第一个b比较是否相等,不等 (若相等则继续在第二行后取长度为1的子串比较,碰到不等为止)则
// (两个长度的子串)第一行ab与第三行首位两个ab比较,相等,继续在第三行取长度为2的子串比较,碰到c不够终止。。
// (三个长度的子串)以此类推···········
//第二趟:第二行的b开始于第三行的c比较········
//abababc
//bababc
//ababc
//babc
//abc
//bc
//利用后缀数组后缀数组是一种数据结构,对一个字符串生成相应的后缀数组后,然后再排序,排完序依次检测相邻的两个字符串的开头公共部分。
//这样的时间复杂度为:总的时间复杂度是 O(N^2*logN),
//后缀数组,每一行比上一行少一个,跳行就可出现少2个、3个……
//第一趟:(一个长度的子串)第一行a与第二行第一个b比较是否相等,不等 (若相等则继续在第二行后取长度为1的子串比较,碰到不等为止)则
// (两个长度的子串)第一行ab与第三行首位两个ab比较,相等,继续在第三行取长度为2的子串比较,碰到c不够终止。。
// (三个长度的子串)以此类推···········
//第二趟:第二行的b开始于第三行的c比较········
//abababc
//bababc
//ababc
//babc
//abc
//bc
//c
pair<int, string> fun(const string &str) { vector<string> substrs; int len = str.length(); string substring; int maxcount(0); //后缀数组 cout << "the string is:" << str << endl; cout << "the substrings are as follows:" << endl; for (int i = 0; i < len; ++i) { substrs.push_back(str.substr(i)); cout << substrs[i] << endl; } cout << "--------------the answer------------" << endl; for (int i = 0; i < len; ++i) { for (int j = i + 1; j < len; ++j) { int count = 1; int sublen = j - i; int lens = substrs[j].length(); for (int k = 0; k < lens; k += sublen) { if (substrs[i].substr(0,sublen) == substrs[j].substr(k,sublen)) { ++count; } else { break; } } //比较最大连续出现次数,并记录相应的子串 if (count>maxcount) { maxcount = count; substring = substrs[i].substr(0, sublen); } } } return make_pair(maxcount, substring); } int main() { string str = ""; auto res = fun(str); cout << "the max count is:" << res.first << endl; cout << "the matched substring is:" << res.second << endl; }