知识点:KMP算法
难度:4
这个题其实就是求个next数组,然后判断的时候用字符串哈希判断一下就行了,应该是可以用别的方法做的,但是我刚学了KMP那就用KMP做吧
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int N = 1e6 + 5;
const int P = 131;
int ne[N];
ull h[N], p[N];
string s;
void init(int len) {
h[0] = 0;
p[0] = 1;
for (int i = 1; i <= len; i++) {
h[i] = h[i - 1] * P + s[i];
p[i] = p[i - 1] * P;
}
}
ull get(int l, int r) {
return h[r] - h[l - 1] * p[r - l + 1];
}
int main() {
while (cin >> s && s != ".") {
s = " " + s;
int len = (int) s.size() - 1;
init(len);
ne[1] = 0;
for (int i = 2, j = 0; i <= len; i++) {
while (j && s[i] != s[j + 1]) j = ne[j];
if (s[i] == s[j + 1]) j++;
ne[i] = j;
}
int Min = N, ans = 1;
int ind = len;
while (ne[ind]) {
int t = ne[ind];
if (len % ne[ind] == 0) {
int ok = 1;
for (int i = 1; i <= len - t + 1; i += t) {
if (get(i, i + t - 1) != get(1, t)) { ok = 0; break; }
}
if (ok) {
Min = t;
ans = len / Min;
}
}
ind = ne[ind];
}
cout << ans << endl;
}
return 0;
}