POJ2752(KMP)

来源:互联网 发布:公司软件著作权转让 编辑:程序博客网 时间:2024/06/08 15:16

大意:给定一个字符串,求所有可能的既是前缀又是后缀的字串长度。

分析:按题目的意思很像求KMP中的next数组。next[len]是最大的前缀-后缀字符串长度,以此类推next[next[len]]同样为满足条件的前缀-后缀字符串长度。

代码

#include <iostream>#include <cstdio>#include <cstring>using namespace std;char str[400005];int len, next1[400005], ans[400005];void getnext(){int i = 0, j = -1;next1[0] = -1;while (i < len){if (j == -1 || str[i] == str[j]){i++;j++;next1[i] = j;}elsej = next1[j];}}int main(){while (scanf("%s", str) != EOF){len = strlen(str);getnext();ans[0] = len;int n = 0, i = len;while (next1[i] > 0){ans[++n] = next1[i];i = next1[i];}for (i = n; i >= 0; i--)printf("%d ",ans[i]);printf("\n");}return 0;}


0 0
原创粉丝点击