码迷,mamicode.com
首页 > 其他好文 > 详细

求一个字符串中连续出现次数最多的子串

时间:2015-08-06 22:31:49      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

技术分享总体思路是:

        首先把给出的字符串按每次减少一个头部字符的方式存入vector中,然后开始在vector[0]中遍历以a开头的子串连续出现的次数。比较的方式为那vector[0]以a开头的一个字符和vector[1]内的比较 如果有 继续 没有 比较以ab开头的子串 。依次类推。

//vector向量中的插入str的后缀数组:
/*后缀数组如:abababc ,bababc,ababc,babc,abc,bc,c*/
#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 - i));//把str字符串中的子串按每次吧头部减少一个的方式插入到vector向量中,string substr(int pos = 0,int n = npos) const;//返回pos开始的n个字符组成的字符串
cout << substrs[i] << endl;
}
for (i = 0; i < len; i++)//先从第一个子串开始直到所有的遍历完所有的子串
{
for (int j = i + 1; j < len/2+1; j++)//从下一个子串开始,寻找连续出现的子串
{
count = 1;
if (substrs[i].substr(0, j - i) == substrs[j].substr(0, j - i))//本题中,寻找以a开头的子串,下面依次为b开头的子串,c开头的子串
{
++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;//如果有连续一个子串出现就遍历vector的下一个子串中的和现在出现相同子串的地方的下一个或几个字符
else
break;
}
if (count > maxcount)//maxcount记录所有遍历中的最大连续子串出现的次数
{
maxcount = count;
substr = substrs[i].substr(0, j - i);
}
}
}
}
return make_pair(maxcount, substr);//把maxcout和找到的子串做成pair<>返回


}
int main()
{
pair<int, string> result;
string str = "abcbcbcbca";
result = fun(str);
cout << result.first << " " << result.second << endl;
system("pause");
return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

求一个字符串中连续出现次数最多的子串

标签:

原文地址:http://blog.csdn.net/wangfengfan1/article/details/47321867

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!