基本概念:
字符串的前缀是指字符串的任意首部。字符串“abbc”的前缀有“a”,“ab”,“abb”,“abbc”。
字符串的后缀是指字符串的任意尾部。字符串“abbc”的后缀有“c”,“bc”,“bbc”,“abbc”。
基本算法描述: 例如给出一个字符串abababa 求连续出现次数最多的子串。
1、穷举出所有的后缀子串
substrs[0] = abababa;
substrs[1] = bababa;
substrs[2] = ababa;
substrs[3] = baba;
substrs[4] = aba;
substrs[5] = ba;
substrs[6] = a;
2、然后进行比较
substrs[0]比substrs[1]多了一个字母,如果说存在连续匹配的字符,那么
substrs[0]的第1个字母要跟substrs[1]首字母匹配,同理
substrs[0]的前2个字母要跟substrs[2]的前2个字母匹配(否则不能叫连续匹配)
substrs[0]的前n个字母要跟substrs[n]的前n个字母匹配.
如果匹配的记下匹配次数。如此可以求得最长连续匹配子串。
实现代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
pair<int, string> MaxSubStr(const string &str)
{
vector<string> substrs;//向量存储后缀子串
int maxcount = 1, count = 1;
string substr;
int i, len = str.length();//字符串长度
//建立所有后缀子串并打印
for(i=0; i<len; ++i)
//substr函数复制子字符串:从指定位置i开始,并具有指定的len-i长度
substrs.push_back(str.substr(i, len-i));
for(i=0; i<len; ++i)
cout<<"substrs["<<i<<"] = "<<substrs[i] << endl;
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()
{
pair<int, string> rs;
string str="abababababaccccc";
rs = MaxSubStr(str);
cout << rs.second<<':'<<rs.first<<'\n';
return 0;
}
结果:
substrs[0] = abababababaccccc
substrs[1] = bababababaccccc
substrs[2] = ababababaccccc
substrs[3] = babababaccccc
substrs[4] = abababaccccc
substrs[5] = bababaccccc
substrs[6] = ababaccccc
substrs[7] = babaccccc
substrs[8] = abaccccc
substrs[9] = baccccc
substrs[10] = accccc
substrs[11] = ccccc
substrs[12] = cccc
substrs[13] = ccc
substrs[14] = cc
substrs[15] = c
ab:5
Process returned 0 (0x0) execution time : 0.259 s
Press any key to continue.