KMP算法

# 微信搜索公众号Corux,和我交朋友!

next[j]的含义是当主串中的第i个字符与模式中的第j个字符失配时,主串中的第i个字符应该与模式中哪个字符再比较,换句话说,next[j]表示当模式中的第j个字符与主串中相应的字符失配时,在模式中需重新和主串中该字符进行比较的字符的位置。

//主串:primary string,简记为prmr_str
//模式串:pattern string,简记为pttn_str
int kmp(string prmr_str, string pttn_str, int pos, int* next) {
	int i = pos, j = 0;
	while (i < prmr_str.length() && j < pttn_str.length()) {
		if (j == -1 || prmr_str[i] == prmr_str[j]) { ++i; ++j; } //j==-1时,第一个字符也不匹配,这时需要将模式串继续滑动
		else j = next[j];
	}
	return j == pttn_str.length() ?
		i - pttn_str.length() : -1;	//返回-1表示没找到
}

KMP算法是在已知模式串的next数组的基础上执行的,那么如何求next数组呢?

我们考虑一般情况,找出next数组的递推关系,即通过next[j]得出next[j + 1].

假设当模式串匹配到j+1位置时与主串失配了,即模式串next[j + 1]位置与主串i位置的字符不匹配,但当前模式串中从0到j位置的字符与主串中对应位置的字符均匹配,此时next[j + 1]的求法:

int k = j;
while ((k = next[k]) != -1 && pttn_str[j] != pttn_str[k]);
next[j + 1] = k + 1;

则next数组整体的求法:

int* get_next(string s) {
	int len = s.length();
	int* next = new int[len];
	
    next[0] = -1;
	for (int j = 0; j != len - 1; ++j) {
		int k = j;
		while ((k = next[k]) + 1 && s[j] != s[k]);
		next[j + 1] = k + 1;
	}

	return next;
}

另一种写法:

int* get_next(string s) {
	int len = s.length();
	int* next = new int[len];

	int i = 0, j = -1;
	next[0] = -1;
	while (i < len - 1) {
		if (j == -1 && s[i] == s[j]) {
			++i; ++j;
			next[i] = j;    //***
		}
		else j = next[j];
	}

	return next;
}

在上述代码的星标位置考虑这样一种情况:模式串 i 位置的字符失配了,如果 j 位置的字符与 i 位置的字符相同,那么执行next[i] = j 之后仍然会失配,那么这步操作就相当于是一次无效的、多余的操作。为了避免这种情况,我们可增加一个条件判断:

if(s[i] != s[j]) next[i] = j;
else next[i] = next[j];

因此求next数组的完整版代码如下所示:

int* get_next(string s) {
	int len = s.length();
	int* next = new int[len];

	int i = 0, j = -1;
	next[0] = -1;
	while (i < len - 1) {
		if (j != -1 && s[i] == s[j]) {
			++i; ++j;
			if (s[i] != s[j]) next[i] = j;
			else next[i] = next[j];
		}
		else j = next[j];
	}

	return next;
}

最终简化版:

int* get_next(string s) {
	int len = s.length();
	int* next = new int[len];

	int i = 0, j = -1;
	next[0] = -1;
	while (i < len - 1)
		j + 1 && s[i] != s[j] ?
		j = next[j] : next[i] = s[++i] != s[++j] ? j : next[j];

	return next;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值