POJ - 2406:Power Strings

Power Strings

来源:POJ

标签:KMP算法

参考资料:

相似题目:

题目

Given two strings a and b we define ab to be their concatenation. For example, if a = “abc” and b = “def” then ab = “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).

输入

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.

输出

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

输入样例

abcd
aaaa
ababab
.

输出样例

1
4
3

提示

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

解题思路

参考KMP算法中求next数组的思路。

参考代码

#include
#include
#define MAXN 1000005
char str[MAXN];
int next[MAXN];

void getNext(char *T){
	int i=0, j=-1;
	int len=strlen(T);
	next[0]=-1;
	while(i<len){ //注意在本题中,要考虑整个字符串,所以此处为i
		if(j==-1 || T[i]==T[j]) {
			++i; ++j;
			next[i]=j;
		}
		else j=next[j];
	}
}

int main(){
	while(gets(str)!=NULL && str[0]!='.'){
		getNext(str);
		int len=strlen(str);
		if(len%(len-next[len])==0) printf("%d\n", len/(len-next[len]));
		else printf("1\n");
	}
	return 0;
}

你可能感兴趣的:(【记录】算法题解)