题意:求一个字符串是由最多多少个小字符串重复构成的。比如ababab就是由3个ab构成的。
根据KMP中next的定义,只要len % (len - next[len]) == 0就说明字符串能被[next[len]~len]的子串构成,所以直接求就行了。
代码:
/*
* Author: illuz <iilluzen[at]gmail.com>
* Blog: http://blog.youkuaiyun.com/hcbbt
* File: poj2406.cpp
* Create Date: 2013-11-27 17:16:02
* Descripton: kmp
*/
#include <cstdio>
#include <cstring>
const int MAXN = 1e6 + 1;
char P[MAXN];
int f[MAXN];
void getVal(int l) {
int i = 0, j = -1;
f[0] = -1;
while (i < l) {
if (j == -1 || P[i] == P[j]) {
i++;
j++;
f[i] = j;
} else
j = f[j];
}
}
int main() {
while (~scanf("%s", P) && P[0] != '.') {
int len = strlen(P);
getVal(len);
if (len % (len - f[len]) == 0)
printf("%d\n", len / (len - f[len]));
else
puts("1");
}
return 0;
}