POJ 2406 Power Strings(KMP)

来源:互联网 发布:三国战记网络联机 编辑:程序博客网 时间:2024/05/14 15:46

Power Strings

题目链接:

http://poj.org/problem?id=2406

解题思路:

next[]数组表示模式串如果第j位(设str[0]为第0位)与文本串第i位不匹配则要回到第next[j]位继续与文本串第i位匹配。所以,如果n%(n-next[n])==0,则存在重复连续子串,长度为n-next[n]。

例如:a    b    a    b    a    b

next:   -1   0    0    1    2    3    4

next[n] == 4,代表着,前缀abab与后缀abab相等的最长长度,这说明,ab这两个字母为一个循环节,长度 = n-next[n]。。。

AC代码:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;char str[1000005];int Next[1000005];void getnext(){    int j = 0,k = -1;    int l = strlen(str);    Next[0] = -1;    while(j < l){        if(k == -1 || str[j] == str[k]){            j++;k++;            Next[j] = k;        }        else            k = Next[k];    }}void kmp(){    getnext();    int l = strlen(str);    if(l % (l-Next[l]) == 0)        printf("%d\n",l/(l-Next[l]));    else        printf("1\n");}int main(){    while(~scanf("%s",str)){        if(str[0]=='.')            break;        kmp();    }    return 0;}



0 0
原创粉丝点击