一道KMP题目
求出next数组后就可以得知一个字串的最长前缀-后缀字串
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read(){
int x=0,f=1,ch=getchar();
while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}
while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();}
return x*f;
}
char s[400005];
int len,nxt[400005];
inline void get_nxt(){
nxt[0]=-1;
int i=0,k=-1;
while(i<len){
if(k==-1||s[i]==s[k]) nxt[++i]=++k;
else k=nxt[k];
}
}
inline void get_ans(int x){
if(x==0) return ;
get_ans(nxt[x]);
printf("%d ",x);
}
int main(){
while(scanf("%s",s)!=EOF){
// puts("X");
len=strlen(s);
get_nxt();
get_ans(len);
puts("");
}
return 0;
}
POJ 2752 Seek the Name, Seek the Fame
原文:https://www.cnblogs.com/gcyyzf/p/9741000.html