题目链接:http://poj.org/problem?id=2752
解题思路:
求所有的相同前后缀长度
求出失配数组,沿着失配数组回退直到等于0,最后答案倒序输出一下。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 4e5 + 5;
char s[N];
int fail[N];
int ans[N];
void kmp(char *s)
{
int tot = 0;
int len = strlen(s);
ans[tot++] = len;
fail[0] = -1;
for (int i=0,j=-1;i<len;){
if (j==-1||s[i]==s[j]){
i++;j++;
fail[i] = j;
}
else j = fail[j];
}
int now = len;
//printf("now=%d,fail[now]=%d\n",now,fail[now]);
while (fail[now]){
//printf("now=%d,fail[now]=%d\n",now,fail[now]);
ans[tot++] = fail[now];
now = fail[now];
}
for (int i=tot-1;i>=0;i--)
if (i!=0) printf("%d ",ans[i]);
else printf("%d",ans[i]);
printf("\n");
}
int main()
{
while (~scanf("%s",s)){
kmp(s);
}
return 0;
}