#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/****************************************************************
功能:写一个函数,找出一个字符串中最长的连续重复子串。
Exmaple:
Input: abcabbcabc
output: 2:bcab
原理:
substr0 abcabbcabc
substr1 bcabbcabc
substr2 cabbcabc
substr3 abbcabc
substr4 bbcabc
substr5 bcabc
substr6 cabc
substr7 abc
substr8 bc
substr9 c
****************************************************************/
pair<int,string> fun(const string& str)
{
vector<string> substrs; // vecotr
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 (count> maxcount)
{
maxcount = count;
substr = substrs[i].substr(0,j-i);
}
}
}
}
return make_pair(maxcount,substr);
}
int _tmain(int argc, _TCHAR* argv[])
{
string str;
pair<int,string> rs;
cout<<"Please Input a string:";
while(cin>>str)
{
rs = fun(str);
cout<<rs.second<<":"<<rs.first<<'\n';
cout<<"Please Input a string:";
}
return 0;
}
// 运行结果