分析:一个字符也算是字串,然而这是求连续最多的子串,abcbcbc,出现最多的为bc,连续出现3次,而如果是abcaaaaa,则a是出现次数最多的,次数为5.
可以首先逐个子串扫描来记录每个子串出现的次数。如:abc字符串,对应的子串为abc/bc/c,各出现一次,然后再逐渐缩小字符串来得出正确的结果。
代码如下:
#include "stdafx.h"
#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();
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 (maxcount < count)
{
maxcount = count;
substr = substrs[i].substr(0,j-i);
}
}
}
}
return make_pair(maxcount,substr);
}
int main()
{
string str;
pair<int,string> rs;
while (cin>>str)
{
rs = fun(str);
cout<<rs.second<<":"<<rs.first<<"\n";
}
return 0;
}
结果: