Power Strings -------- POJ 2406

Description

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).

Input

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.

Output

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

Sample Input

abcd
aaaa
ababab
.

Sample Output

1
4
3

 題意:詢問每個字符串最多是由多少個相同的子字符串重複連接而成的,如:ababab 則最多有 3 個 ab 連接而成。(即求循環節             的個數)。

思路:針對於KMP, 模式串如果第j位與文本串第i 位不匹配,就要回到第next[j]位繼續與文本串的第j位匹配,

           則模式串第1~next[j]位是與模式串第(n-next[n])位到n位是匹配的。

           所以如果n%(n-next[n])==0,則存在重複連續子串,長度爲n-next[n],循環次數爲n/(n-next[n])。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
char s[1000010];
int nex[1000010];
int main()
{
    while(~scanf("%s",s))
    {
        memset(nex,0,sizeof(nex));
        if(strcmp(s,".")==0) break;
        int l=strlen(s);
        int i=0,j=-1;
        nex[0]=j;
        while(i<l)
        {
            if(j<0||s[i]==s[j])
                nex[++i]=++j;
            else
                j=nex[j];
        }
        if(l%(l-nex[l])==0)
        {
            printf("%d\n",l/(l-nex[l]));
        }
        else
            printf("%d\n",1);

    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章