#KMP#poj 2752 Seek the Name, Seek the Fame

题目

求长度多少的前缀与相同长度的后缀相等。


分析

kmp,字符串匹配,沿着p[j]跳回去。


代码

#include <cstdio>
#include <cstring>
using namespace std;
char a[400001]; int p[400001];
void dfs(int j){
    if (j<0) return; else dfs(p[j]),printf("%d ",j+1);
}
int main(){
    while (scanf("%s",a)!=EOF){
        p[0]=-1; int l=strlen(a);
        for (int i=1,j=-1;i<l;i++){
            while (j>=0&&a[j+1]!=a[i]) j=p[j];
            if (a[j+1]==a[i]) j++; p[i]=j;
        }
        dfs(p[l-1]); printf("%d\n",l);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sugar_free_mint/article/details/80755634
今日推荐