POJ 2752 Seek the Name, Seek the Fame kmp算法

来源:互联网 发布:js url转base64编码 编辑:程序博客网 时间:2024/06/05 10:37

题目:http://poj.org/problem?id=2752

题意:给定一个字符串,求这个字符串前缀等于后缀时的长度(前缀或后缀长度)

思路:用next数组性质可做,画个图很容易看出来

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 400010;char s[N];int nt[N];void getnt(){    int i = 0, j = -1;    nt[0] = -1;    while(s[i])    {        if(j == -1 || s[i] == s[j])            i++, j++, nt[i] = j;        else j = nt[j];    }}int main(){    while(~ scanf("%s", s))    {        getnt();        int len = strlen(s);        int ans[N], k = 0;        while(len != 0)            ans[k++] = len, len = nt[len];        for(int i = k - 1; i >= 0; i--)            printf("%d%c", ans[i], i == 0 ? '\n' : ' ');    }    return 0;}


0 0