题意:
从一个串s中找出一个最长的子串t,该字串满足:1.t是s的前缀2.t是s的后缀.3t在s串中即不是前缀也不是后缀
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
题解:KMP+扩展KMP中的next数组的应用。
利用KMP的next数组可以求出以s[i]为结尾的字串和s串最长的匹配长度。利用扩展KMP的next数组可以求出以s[i]为开始的子串和s串最长的匹配长度。
正着做一遍KMP,反着做一次E-KMP,然后即可O(1)判定以s[i]为结尾的子串和s串最长的匹配的串t,如果a[len-i+1]>=next[i],即证明t也是该串的后缀。
总之,就是用KMP判断是否为前缀,E-KMP判断是否为后缀。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int next[2000001];
int next2[2000001];
char b[2000001],tb[2000001];
int a[2000001];
int main()
{
while(scanf("%s",b)!=EOF)
{
int bn=strlen(b);
//KMP
memset(next, 0, sizeof(next));
for(int i = 1; i < bn; i++)
{
int temp = next[i - 1];
while(temp && b[temp] != b[i])temp = next[temp - 1];
if(b[temp] == b[i])next[i] = temp + 1;else next[i] = 0;
}
for(int i=0;i<bn;i++)
tb[i]=b[bn-i-1];
//E_KMP
int j = 0;
while(tb[0+j]==tb[1+j]) j = j + 1;
a[1]=j;
int k=1;
for(int i=2;i<bn;i++)
{
int Len=k+a[k]-1,L=a[i-k];
if( L < Len - i + 1 ) a[i] = L;
else
{
j = max(0,Len -i +1);
while(tb[i+j]==tb[0+j]) j = j + 1;
a[i] = j,k = i;
}
}
int maxl=0,pos=0;
for(int i=0;i<bn;i++)
if(next[i]>0)
{
int tpos=bn-i-1;
if(a[tpos]>=next[i])
{
if(next[i]>maxl)
{
maxl=next[i];
pos=i;
}
}
}
if(maxl==0)printf("Just a legend\n");else
{
for(int i=pos-maxl+1;i<=pos;i++)
printf("%c",b[i]);
printf("\n");
}
}
return 0;
}