求一个字符串中连续出现次数最多的字串

来源:互联网 发布:电脑动态桌面软件推荐 编辑:程序博客网 时间:2024/06/07 22:26
#include<iostream>#include<vector>#include<string>using namespace std;pair<int, string> fun(const string &str){vector<string> substrs;int maxcount = 1;int count =1;string substr;int i, len = str.length();for (i = 0; i < len; ++i){substrs.push_back(str.substr(i, len - i));}for (i = 0; i < len; ++i){for (int j = i + 1; j < len; ++j){count = 1;if (substrs[i].substr(0, j - i) == substrs[j].substr(0, j - i)){++count;for ( int k = j + (j - i); k < len; k+=j - i){if ( substrs[i].substr(0, j - i) == substrs[k].substr(0, j - i)){++count;}else{break;}}if (count > maxcount){maxcount = count;substr = substrs[i].substr(0, j - i);}}}}return make_pair(maxcount, substr);}int main(void){string str = "abcbcbcabc";pair<int, string> rs;rs = fun(str);cout<<rs.second<<":"<<rs.first<<endl;return 0;}