链接:http://poj.org/problem?id=2752
题意:一个字符串,求所有相同的前缀后缀长度,并从小到大输出。
分析:KMP的next[]数组应用。
Source Code:
#include<stdio.h> #include<string.h> #define maxn 1000010 char s[maxn]; int next[maxn],ans[maxn],len; void GetNext(){ int j=0,k=-1; next[0]=-1; while(j<len){ if(k==-1||s[j]==s[k]){ j++,k++; next[j]=k; } else k=next[k]; } } int main() { int idx,tot,i; while(scanf("%s",s)!=EOF){ len=strlen(s); GetNext(); tot=0; idx=next[len]; if(idx>0) ans[tot++]=idx; while(next[idx]>0){ ans[tot++]=next[idx]; idx=next[idx]; } for(i=tot-1;i>=0;i--) printf("%d ",ans[i]); printf("%d\n",len); } return 0; }