首先要搞清楚题目关于子串的概念。
1.一个字符当然也算子串。而题目要求连续出现次数最多的子串。
如:abcbcbcabc,连续出现次数最多的子串是bc,连续出现三次。
abcccabc,连续出现次数最多的子串是c,连续出现三次。
算法描述
首先获得后缀数组:
a b c b c b c a b c .substr[0]
b c b c b c a b c ....substr[1]
c b c b c a b c .......substr[2]
b c b c a b c ..........substr[3]
c b c a b c .............substr[4]
b c a b c ...............substr[5]
c a b c .................substr[6]
a b c.. ...................substr[7]
b c ........................substr[8]
c............................substr[9]
然后
1.第一行第一个字符a,与第二行第一个字符b比较,不等,则
2.第一行前两个字符ab,与第三行前两个字符cb比较,不等,则
3.第一行前三个字符abc,与第四行前三个字符bcb比较,不等,则
4.第一行前四个......
上述过程就相当于在原始字符串中,
第一趟,a与b比较,ab与cb比较,abc与bcb比较,abcb与cbca比较,abcbc与bcabc比较,abcbcb与cabc比较......
第二趟,b与c比较,bc与bc比较(相等,则继续向后取长度为2的子串比较,碰到不等为止,本例中因碰到ab停止),bcb与cbc比较......
第三趟,c与b比较,cb与cb比较(相等),cbc与bca比较......
代码实现:
#include <iostream>
#include <string>
using namespace std;
void main(){
string str = "abcabcabcccccdefefefefefef";
int len = str.length();
int maxCount = 1;
string longest = "";
for (int pos1 = 0; pos1 < len; pos1++)
for (int pos2 = pos1 + 1; pos2 < len; pos2++)
{
if (str.substr(pos1, pos2 - pos1) == str.substr(pos2, pos2 - pos1+1))
{
int offset = pos2 - pos1;
int count = 2;
for (int k = pos2 + offset; k < len; k += offset)
{
if (str.substr(pos1, offset) == str.substr(k, offset))
{
count += 1;
}
else
{
break;
}
}
if (count > maxCount)
{
maxCount = count;
longest = str.substr(pos1, offset);
}
}
}
cout << longest << " 出现次数:" << maxCount << endl;
system("pause");
}
#include <iostream>
#include <vector>
#include <string>
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));
cout << substrs[i]<<endl;
}
for (i = 0; i<len; ++i)
{
for (int j = i + 1; j<len; ++j)
{
count = 1;
int offset=j-i;//offset 表示当前统计字符串长度
if (substrs[i].substr(0, offset) == substrs[j].substr(0, offset))
{
++count;
for (int k = j + offset; k<len; k += offset)
{
if (substrs[i].substr(0, offset) == substrs[k].substr(0, offset))
++count;
else
break;
}
if (count>maxcount)
{
maxcount = count;
substr = substrs[i].substr(0, offset);
}
}
}
}
return make_pair(maxcount, substr);//生成pair
}
int main()
{
string str;
pair<int, string> rs;
str = "abcabcabcccccdefefefefefef";
rs = fun(str);
cout << rs.second << ':' << rs.first << endl;
system("pause");
return 0;
}