Power Strings POJ - 2406(字符串周期)

题目:

Description

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

题意:给一个字符串,求它的最小周期,输出共重复出现多少次,即总长度除以最小周期的长度。

字符串周期问题用简单的next数组即可,不用改进的next数组

 

代码:

#include
#include
using namespace std;

char c[1000001];
int next_[1000001];
int l;

void get_next(char *t, int m, int next[])
{
	int i = 1, j = 0;
	next[0] = next[1] = 0;
	while (i < m)
	{
		if (j == 0 || t[i] == t[j])next[++i] = ++j;
		else j = next[j];
	}
}

int main()
{
	while (cin >> c + 1)
	{
		if (c[1] == '.')break;
		l = strlen(c + 1);	
		get_next(c, l, next_);
		int dif = l - next_[l];
		if (l%dif)cout << 1;
		else if (c[l] == c[next_[l]])cout << l / dif;
		else cout << 1;
		cout << endl;
	}
	return 0;
}

 

 

你可能感兴趣的:(Power Strings POJ - 2406(字符串周期))