MOOC第四章、字符串测验

题目

上一题中的字符串"BAAABBBAA",与目标"BAAABBBCDDDCCHHHHBBBAAABBBAADD"进行匹配,至少需要多少次字符匹配(提示:利用优化后的Next数组):
The string in question above “BAAABBBAA” matches with “BAAABBBCDDDCCHHHHBBBAAABBBAADD”. How many times character matching will need at least? (Hint: Use “Next” arrays ):

答案

31

过程

先来回忆一下计算next数组的代码
优化前的

int *findNext(string P) {
	int j, k;
	int m = P.length();
	assert(m > 0);
	int *next = new int[m];
	assert(next != 0);
	next[0] = -1;
	j = 0, k = -1;
	while (j < m - 1) {
		while (k >= 0 && P[k] != P[j])
			k = next[k];
		j++;
		k++;
		next[j] = k;
	}
	return next;
}

优化后的

int *findNext(string P) {
	int j, k;
	int m = P.length();
	assert(m > 0);
	int *next = new int[m];
	assert(next != 0);
	next[0] = -1;
	j = 0, k = -1;
	while (j < m - 1) {
		while (k >= 0 && P[k] != P[j])
			k = next[k];
		j++;
		k++;
		//有区别的地方
		if(P[k]==P[j]){
			next[j]=next[k]

		}else{
			next[j]=k;
		}
	}
	return next;
}

解答过程在这里插入图片描述
1.先求出优化前的next数组,下标含义是前面串的串首和串尾的相同字符个数,
以j=8为例,[BA]AABB[BA],括号里面的相等,所以next[8]=2。
2.根据优化前的next数组求出优化后的next数组,按照这段代码计算

if(P[k]==P[j]){
	next[j]=next[k]

}else{
	next[j]=k;
}

1.如果Pk!=Pj,next[j]=k
以j=1为例,此时k是优化前的next[j]=0,Pj=P1=‘A’,Pk=P0=‘B’,所以,next[1]=0
2.如果Pk==Pj,next[j]=next[k]
以j=4为例,k=0,next[4]=next[0]=-1

然后匹配
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值