求一个字符串中连续出现次数最多的子串
2015-08-06 20:42
302 查看
总体思路是:
首先把给出的字符串按每次减少一个头部字符的方式存入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;
}
相关文章推荐
- HDOJ 1222 Wolf and Rabbit(数学解题技巧)
- android 当屏幕截图,你如何改变屏幕内容,他们俩bitmap将合并的图像被一起显示
- hdu 1575 try a 矩阵快速幂
- Linux uniq 命令
- leetcode_Sqrt(x)
- 2015 Multi-University Training Contest 2
- 生成函数小结
- CodeForces #Pi C.Geometric Progression
- 编写主引导扇区代码
- 浅谈算法和数据结构: 一 栈和队列
- 第十五天 简单聊天
- DWR:java.lang.SecurityException: Class not found
- HDU-4786 Fibonacci Tree
- 2015第32周四
- (转载)深度学习三十年创新路
- centos 安装卸载软件命令 & yum安装LAMP环境
- java将日期格式字符串2015-08-05T09:40:00+08:00转换为yyyy-MM-dd HH:mm:ss
- IOS性能优化
- 浅谈算法和数据结构: 二 基本排序算法
- D. One-Dimensional Battle Ships-二分答案-Codeforces Round #Pi (Div. 2)