【kmp算法】求一个串的重复子串

http://poj.org/problem?id=1961

题意:在给定的字符串前i位找出循环节断的个数。

思路:还是kmp算法的应用变形,从给出字符串的第2位开始遍历,找出每次的匹配的字符串(length),前i为字符串长度为i,所以i/length就是循环节断的个数,要保证i/length能够整除,所以i%length==0。


移动位数(length)   =     已匹配的字符数(i)  -    对应部分匹配值(next[i])

【参考代码】

#include<cstdio>
#include<cstring>
using namespace std;

const int Max=1000001;
char str[Max];
int next[Max];

void getnext(int n)
{
	int i=0,j=-1;
	next[i]=-1;
	while(i<n) {
		if(j==-1||str[i]==str[j]) {
			next[++i]=++j;
		}
		else j=next[j];
	}
}

int main()
{
	int len,cas=0;
	while(scanf("%d",&len)&&len) {
		scanf("%s",str);
		getnext(len);
		printf("Test case #%d\n",++cas);
		for(int i=1;i<=len;i++) {
			int length=i-next[i];
			if(i!=length&&i%length==0)
				printf("%d %d\n",i,i/length);
		}
		printf("\n");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值