从最长的字符串开始找,设len为字符串长度,
步骤1、长度为len的字符串,L=len
步骤2、长度为len-1的字符串,L=len-1
步骤3、长度为len-2的字符串,L=len-2
....
步骤L、长度为L的字符串
.....
步骤len、长度为1的字符串,L=1
设置一个变量i,用来指示子字符串的首位置,子字符串的范围为 :i—i+L-1,i取值从0到len-L+1
#include <iostream>
#include <string>using namespace std;
void main()
{
string str,tmp;
cout<<"输入字符串"<<endl;
cin>>str;
int len=str.length();
int L=len;
int i=0;
int f,b;
while(L>0)
{
for(i=0;i+L-1<len;i++)
{
tmp=str.substr(i,i+L-1);
f=str.find(tmp);
b=str.rfind(tmp);
if(f!=b)
{
cout<<tmp<<' '<<i<<endl;
L=0;//结束
break;
}
}
L--;
}
system("pause");
}