字符串练习:Password
Cry_For_theMoon · · 题解
传送门
大佬们都打什么 Z 算法,我这个蒟蒻只能用 KMP 来水一发
我们注意到"前后缀"都是可以直接用 KMP 里的
若在中间的字串
又因为中间的那个字串
那么这个 Just a legend 即可。
当我们当前的长度
原因何在?回想一下我们
那么我们就得出了一个结论:1~maxn 这些值都存在于
最后贴上AC代码,供各位 dalao 参考
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=1e6+10;
char str[MAXN];
int fail[MAXN],n,maxn=0;
int main(){
cin>>(str+1);
n=strlen(str+1);
fail[1]=0;
int j=0;
for(int i=2;i<=n;i++){
while(j&&str[j+1]!=str[i]){
j=fail[j];
}
if(str[j+1]==str[i])j++;
fail[i]=j;
if(i!=n){
maxn=max(maxn,j);
}
}
j=fail[n];
if(maxn==0 || j==0){
printf("Just a legend");
return 0;
}
while(j>maxn){
j=fail[j];
}
if(j==0){
printf("Just a legend");
return 0;
}
for(int k=1;k<=j;k++){
printf("%c",str[k]);
}
printf("\n");
return 0;
}