求解字符串是否是周期串,如果是输出循环了几次。KMP周期问题,循环节是i - next[i]。
代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 1000010;
char s[MAX];
int n,f[MAX];
void getf(){
f[0] = f[1] = 0;
for(int i=1; i<n; i++){
int j = f[i];
while(j && s[i] != s[j]) j = f[j];
f[i+1] = s[i] == s[j] ? j + 1 : 0;
}
}
int main(){
while(scanf("%s",s) == 1 && s[0] != '.'){
n = strlen(s);
getf();
if(f[n] && n % (n - f[n]) == 0) cout << n / (n - f[n]) << endl;
else puts("1");
}
return 0;
}