#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
pair<int,string> fun(const string& str)
{
vector<string> substrs;//存放所有子串
int maxcount=1,count=1;
string substr;
int i,len=str.length();
// cout<<str<<endl;
for(i=0;i<len;++i)
{
cout<<str.substr(i,len-i)<<endl;
substrs.push_back(str.substr(i,len-i));//获取str中从i开始到长度为len-i字符串,即从i开始到最后的字符串
}
for(i=0;i<len;++i)
{
for(int j=i+1;j<len;++j)
{
count=1;
// cout<<"i--j:"<<i<<"---"<<j<<endl;
// cout<<"substrs[i]->"<<substrs[i]<<endl;
cout<<"substrs[i].substr(0,j-i)->"<<substrs[i].substr(0,j-i)<<endl;
// cout<<"substrs[j]->"<<substrs[j]<<endl;
cout<<"substrs[j].substr(0,j-i)->"<<substrs[j].substr(0,j-i)<<endl;
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)//在找到第一个匹配的后,看看后面有没有匹配的
{
// cout<<"substrs[k]->"<<substrs[k]<<endl;
// cout<<"substrs[k].substr(0,j-i)->"<<substrs[k].substr(0,j-i)<<endl;
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(int argc, char *argv[])
{
string str="abcbcbcabc";
pair<int,string> rs;
rs=fun(str);
cout<<rs.second<<':'<<rs.first<<'\n';
system("PAUSE");
return EXIT_SUCCESS;
}
求一个字符串中连续出现次数最多的子串。
最新推荐文章于 2024-11-05 17:16:24 发布