poj 2752 前后缀匹配

kmp才能保证不超时

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <iostream>
using namespace std;

void getNext(int next[],char str[]){
    int j = 0;
    next[0] = -1;
    int k = -1;
    int len = strlen(str);
    while(j < len){
        if(k == -1 || str[k] == str[j]){
            next[++j] = ++k;
        }
        else k = next[k];
    }
}

int main(){
    //freopen("in.txt","r",stdin);
    char str[400001];
    int next[400001];

    int j;
    while(scanf("%s",str) != EOF){
        memset(next,0,strlen(str));
        getNext(next,str);
        stack <int> q;
        j =strlen(str);
        while(j != 0){
            q.push(j);
            j = next[j];
        }
        while(!q.empty()){
            printf("%d ",q.top());
            q.pop();

        }
        printf("\n");
    }

    return 0;
}
posted @ 2015-12-19 14:16  sean10  阅读(174)  评论(0)    收藏  举报