POJ 2752 Seek the Name, Seek the Fame (KMP的next函数,求前缀和后缀的匹配长度)

时间:2023-03-08 18:09:33
POJ 2752 Seek the Name, Seek the Fame (KMP的next函数,求前缀和后缀的匹配长度)

给一个字符串S,求出所有前缀,使得这个前缀也正好是S的后缀。升序输出所有情况前缀的长度。
KMP中的next[i]的意义就是:前面长度为i的子串的前缀和后缀的最大匹配长度。
明白了next[i],那么这道题就很容易做了

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm> using namespace std;
const int maxn=;
char str[maxn];
int next[maxn];
int n;
int ans[maxn];
void getnext(char *str,int len){
next[]=-;
int i=,j=-;
while(i<len){
if(j==- || str[i]==str[j]){
i++;j++;
next[i]=j;
}
else
j=next[j];
}
}
int main()
{
while(scanf("%s",str)!=EOF){
n=strlen(str);
getnext(str,n);
int l=next[n];
int idx=;
ans[idx++]=n;
while(l!=){
ans[idx++]=l;
l=next[l];
}
for(int i=idx-;i>=;i--){
if(i==idx-)
printf("%d",ans[i]);
else
printf(" %d",ans[i]);
}
printf("\n");
}
return ;
}