【Kmp求既是字首又是字尾的子串】POJ - 2752 Seek the Name, Seek the Fame

CN_swords發表於2017-07-26

 Link:http://poj.org/problem?id=2752

#include <cstdio>
#include <cstring>
using namespace std;

/*
POJ - 2752
從小到大輸出滿足既是字首又是字尾的字串長度
next陣列遞迴產生
*/
const int N = 400005;
int nex[N];
void getnext(char *s){
    int k = -1;
    nex[0] = -1;
    int len = strlen(s);
    for(int i = 1; i < len; i++){
        while(k!=-1 && s[k+1]!=s[i])
            k = nex[k];
        if(s[k+1]==s[i])
            k++;
        nex[i] = k;
    }
}
char s[N];
int ans[N];
int main(){
    while(~scanf("%s",s)){
        getnext(s);
        int len = strlen(s);
        int k = 0;
        while(1){
            if(len == 0)
                break;
            else{
                ans[k++] = len;
                len = nex[len-1]+1;
            }
        }
        for(int i = k-1; i >= 0; i--)
            printf("%d%c",ans[i],i==0?'\n':' ');
    }
    return 0;
}


相關文章