题目大意:给你一个字符串,问需要添加多少个字符,才能使这个字符串变成一个至少由2个循环节组成的字符串
解题思路:这题考查的是KMP和循环节的概念,在KMP中,循环节的长度就是len - next[len],len指字符串的长度
得知循环节的长度后,就可以判断该字符串是否已经符合了,也就是不用添加了
如果需要添加的话,添加的长度就是len - next[len] - len % (len - next[len])
#include <cstdio>
#include <cstring>
const int N = 100010;
char str[N];
int next[N];
int len;
void getFail() {
next[0] = -1;
int i = 0, j = -1;
while (i < len) {
if (j == -1 || str[i] == str[j]) {
i++; j++;
next[i] = j;
}
else j = next[j];
}
}
void init() {
scanf("%s", str);
len = strlen(str);
getFail();
}
void solve() {
int t = len - next[len];
if (t != len && len % t == 0) printf("0\n");
else {
int ans = t - len % t ;
printf("%d\n", ans);
}
}
int main() {
int test;
scanf("%d", &test);
while (test--) {
init();
solve();
}
return 0;
}