POJ 2406 Power Strings 最小循环节

一、内容

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n). 

Input

Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case. 

Output

For each s you should print the largest n such that s = a^n for some string a. 

Sample Input

abcd
aaaa
ababab
.

Sample Output

1
4
3

二、思路

在这里插入图片描述

三、代码

#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1e6 + 5;
char s[N];
int n, ne[N];
void getNext() {
	ne[1] = 0;
	for (int i = 2, j = 0; i <= n; i++) {
		while (j && s[i] != s[j + 1]) j = ne[j];
		if (s[i] == s[j + 1]) j++;
		ne[i] = j;
	}
}

int main() {
	while (scanf("%s", s + 1), strcmp(s + 1, ".") != 0) {
		n = strlen(s + 1);
		getNext();
		int len = n - ne[n];
		if (n % len == 0) printf("%d\n", n / len);
		else printf("1\n");
	}
	return 0;
}
发布了495 篇原创文章 · 获赞 511 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_41280600/article/details/104676765