题意:在一个字符串中求一字串,即可以在前缀中找到,也可以在后缀中找到,也可以在中间找到
做法来自自于ZeroClock
#include <iostream>
#include <cstdio>
#include <cstring>
#define LMT 1000005
/****
KMP算法本质:在字符串中有一个字符,以这个字符为末尾的长度为N的子串(不包括末字符,N为所能取到的最大值),
可以与字符串头字符构成的长度为N的字串匹配(不包括末字符,且保证末字符不等)。
***/
//第一次的next是最大的,之后就逐个减小
using namespace std;
int hash[LMT],next[LMT],len;
char str[LMT];
void init(void)
{
int i=0,j=-1;
next[0]=-1;
while(i<len)
{
if(j==-1||str[i]==str[j])
{
i++;j++;next[i]=j;
}
else j=next[j];
}
for(i=0;i<len;i++)
hash[next[i]]++;
}
int main()
{
int i;
scanf("%s",str);
len=strlen(str);
init();
i=len;
while(next[i]>0)
{
if(hash[next[i]])
{
for(int j=0;j<next[i];j++)
printf("%c",str[j]);
printf("\n");
return 0;
}
i=next[i];
}
printf("Just a legend\n");
return 0;
}