首页 > 代码库 > UVA 10298 - Power Strings(KMP)

UVA 10298 - Power Strings(KMP)

UVA 10298 - Power Strings

题目链接

题意:本意其实就是,给定一个字符串,求出最小循环节需要几次循环出原字符串

思路:利用KMP中next数组的性质,n - next[n]就是最小循环节,然后n / 循环节就是答案

代码:

#include <cstdio>
#include <cstring>

const int N = 1000005;
char str[N];
int next[N];

void getnext() {
    int n = strlen(str);
    next[0] = next[1] = 0;
    int j = 0;
    for (int i = 2; i <= n; i++) {
	while (j && str[i - 1] != str[j]) j = next[j];
	if (str[i - 1] == str[j]) j++;
	next[i] = j;
    }
    printf("%d\n", n / (n - next[n]));
}

int main() {
    while (~scanf("%s", str) && strcmp(str, ".") != 0) {
	getnext();
    }
    return 0;
}