例如字符串“abababc”,最多连续出现的为ab,连续出现三次。
求一个字符串中连续出现的次数最多的子串,首先生成后缀数组例如
abababc
bababc
ababc
babc
abc
bc
c
这题跟
后缀数组求最长重复子串 一样都用到了后缀数组。
#include<iostream>
#include<string>
#include<vector>
using namespace std;
pair<int, string> fun(string str){
int len = str.size();
vector<string> subs(len);
for (int i = 0; i < len; i++){
subs[i] = str.substr(i, len - i);
}
int maxSub=0;
string res;
for (int i = 0; i < len; i++){
for (int j = i + 1; j < len; j++){
int cnt = 1;
if (subs[i].substr(0, j - i) == subs[j].substr(0, j - i)){
cnt++;
for (int k = j + (j - i); k < len; k += j - i){
if (subs[i].substr(0, j - i) == subs[k].substr(0, j - i)){
cnt++;
}
else{
break;
}
}
if (cnt>maxSub){
maxSub = cnt;
res = subs[i].substr(0, j - i);
}
}
}
}
return make_pair(maxSub, res);
}
int main(){
string str = "abababc";
pair<int, string> res = fun(str);
cout << res.first << endl;
cout << res.second << endl;
return 0;
}