POJ—2406—kmp(循环节1)

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

           题目大意就是输入字符串,以“ . ”结束,让你求出字符串中循环节的最小长度。

           用 kmp 中的 x = n - nex[n-1] 计算循环节,具体看代码。

#include<stdio.h>
#include<string.h>
const int N = 1000005;
char a[N];
int nex[N],n;

void init()
{
	nex[0] = 0;//nex数组的建立 
	int i = 1,j = 0;
	while(i < n)
	{
		if(a[i] == a[j])
			nex[i++] = ++j;
		else if(!j)
			i++;
		else
			j = nex[j-1];
	}
}

int main()
{
	while(~scanf("%s",a) && a[0]!='.')
	{
		memset(nex,0,sizeof nex);
		n = strlen(a);
		init();
		int x = n - nex[n-1];//下面两部就是当 n % x为 0 的时候代表有循环节 
		if(n % x == 0)
			printf("%d\n",n/x);
		else printf("%d\n",1);//否则就是没有,输出1 
	}
	return 0;
}

还有一种 nex 数组的写法,区别其实也不大,看个人习惯;

1,一个就是初始的建立不同;

2,上面的一个 nex[i] 代表 0 ~ i(包括 i )的最长前后缀,下面的 nex[i]是代表,0 ~ i - 1(包括 i - 1)的写法;

3,第一个 nex 数组下标是 0 ~n -1的,而下面的下标是 0 ~ n,就是使用的时候下标不太一样。

#include<stdio.h>
#include<string.h>
const int N = 1000005;
int nex[N],n;
char a[N];

void init()
{
	int i = 0,j = -1;
	nex[0] = -1;
	while(i < n)
	{
		if(j == -1 || a[i] == a[j])
			nex[++i] = ++j;
		else
			j = nex[j];
	}
}

int main()
{
	while(scanf("%s",a) && a[0] != '.')
	{
		memset(nex,0,sizeof nex);
		n = strlen(a);
		init();
		int x = n - nex[n];
		if(n % x == 0)
			printf("%d\n",n/x);
		else
			printf("1\n");
	}
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值