这个题的意思是让你找到前后缀相同并且除去前后缀字符串中还出现过的最长的字串长度。
这个题我的做法是利用next数组遍历相同的前后缀,然后如果前后缀的长度(单个前缀或后缀,因为二者相同)*3<=len,那么把前缀与前缀后面 后缀前面的(中间的)那个字符串进行匹配,如果匹配到了 那么就输出。
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
char x[1000000+100];
int knext[1000000+100];
void kmp_pre(char x[], int n)
{
int i,j;
i = 0;
j = knext[0] = -1;
while(i<n)
{
while(j!=-1&&x[i]!=x[j])
j =knext[j];
knext[++i] = ++j;
}
}
int solve()
{
int lenx = strlen(x);
//cout<<knext[lenx]<<endl;
if(knext[lenx]==0)
return 0;
int maxs = 0;
int temp = 0;
int t = knext[lenx-1];
int flag = 0;
while(t!=-1)
{
if(x[t]==x[lenx-1])
{
if((t+1)*3<=lenx)
{
//cout<<t+1<<endl;
for(int i = t+1, j =0; i<(lenx)-(t); )
{
while(j!=-1&&x[j]!=x[i])j = knext[j];
++i,++j;
if(j>=t+1){
flag=1;
break;
}
}
}
if(flag)
{
maxs = t+1;
break;
}
}
t = knext[t];
}
return maxs;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",x);
int lenx = strlen(x);
kmp_pre(x,lenx);
int res = solve();
cout<<res<<endl;
}
}
//