Power Strings kmp

来源:互联网 发布:mac的相册导出 编辑:程序博客网 时间:2024/06/03 22:52

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

Hint

题意

题解:

利用kmp中的next数组 (表示最前缀后缀最长匹配长度)
计算该串的next 即next[len]
用总长减去这个值就可以得到非重复串长度 即单位长度
单位长度必须整除总长 否则输出1

AC代码

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MAXN = 1e6+10;char st[MAXN];int nxt[MAXN];void getnext(int m){    int i = 0,j = 0;    nxt[0] = -1;j = nxt[0];    while (i < m){        if (j == -1 || st[i] == st[j]){            nxt[++i] = ++j;        }else j = nxt[j];    }}int main(){    while (scanf("%s",st)!=EOF){        if (st[0]=='.') break;        memset(nxt,0,sizeof(nxt));        int len = strlen(st);        getnext(len);        int d;        d =len-nxt[len];        if (len%d==0) printf("%d\n",len/d);        else printf("1\n");    }    return 0;}
原创粉丝点击