数据结构之KMP算法---poj2406---Power Strings

来源:互联网 发布:mac地址一样 编辑:程序博客网 时间:2024/05/18 00:17

http://poj.org/problem?id=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

abcdaaaaababab.

Sample Output

143
代码实现:

#include<iostream>#include<cstring>#define max 1000001using namespace std;int next[max];char str[max];int getnext(char *str){    int i=0,j=-1;    int len=strlen(str);    next[0]=-1;    while(i<len)    {        if(j==-1||str[i]==str[j])        {            i++;            j++;            next[i]=j;        }        else            j=next[j];    }    i=len-j;    if(len%i==0)        return len/i;    else        return 1;}int main(){    while(cin>>str)    {        if(str[0]=='.')break;        int ans=getnext(str);        cout<<ans<<endl;    }    return 0;}


0 0
原创粉丝点击