要求子串长度大于2,且子串可以出现在任意位置
//输出一个字符串中出现频率最高的子字符串(要求子串长度大于等于2)
#include<iostream>
#include<string>
#include<map>
#include<utility>
using namespace std;
//pair<string,int> fun(string s)
int main()
{
int max=0;
string s;
cin>>s;
map<string,int> strcount;
string subs;
//int count=1;
for(size_t i=2;i<=s.size()/2;i++)
for(size_t j=0;j<s.size()-i;j++)
{
subs=s.substr(j,i);
int count=1;
if(strcount.count(subs)==0)
{
//strcount[subs]=1;
string::size_type pos=j+i;
while((pos=s.find(subs,pos))!=string::npos)
{
count++;
++pos;
}
strcount[subs]=count;
// cout<<subs<<" "<<count<<endl;
}
}
map<string,int>::iterator it=strcount.begin(),object;
for(;it!=strcount.end();++it)
//cout<<it->first<<" "<<it->second<<endl;
if(it->second > max)
{
max=it->second;
object=it;
}
cout<<max<<":"<<object->first<<endl;
}
程序运行结果: