poj_2406 Power Strings(KMP求周期子串)

【题目描述】

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).

【输入输出】

Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.

For each s you should print the largest n such that s = a^n for some string a.

【输入样例】

abcd
aaaa
ababab
.

【输出样例】

1
4
3

【我的解法】

本题考察对KMP算法中next数组的应用:若记字符串长度为sLen,则next[sLen]保存的值为整个串中的最大公共前缀后缀的长度,若字符串由循环子串组成,则sLen-next[sLen]则为最小循环节的长度。

通过下面的测试结果,可以更好理解next数组:

poj_2406 Power Strings(KMP求周期子串)_第1张图片

下面附上代码。

#include <stdio.h>
#include <string.h>

void getNext(char t[], long int next[], long int tLen)
{
    int i=0, j=-1;
    next[i]=j;

    while (i<tLen)
        if (j==-1 || t[i]==t[j])
        {
            i++;j++;
            if (t[i]!=t[j]) next[i]=j; else next[i]=next[j];
        }
        else j=next[j];
}

int main()
{
    char s[1000001];
    long int next[1000001];
    while (scanf("%s",s)!=EOF)
        if (s[0]!='.')
    {
        long int sLen=strlen(s);
        getNext(s,next,sLen);
        if (sLen%(sLen-next[sLen])==0) printf("%ld\n",sLen/(sLen-next[sLen]));
        else printf("1\n");
    }
    return 0;
}


你可能感兴趣的:(算法,KMP,poj,模式匹配,NOI)