KMP算法

定义:
Knuth-Morris-Pratt 字符串查找算法,简称为 KMP算法,常用于在一个文本串 S 内查找一个模式串 P 的出现位置。
运行过程:
以文本串T和模式串S为例
文本串T : a b a c a a b a c a b a c a b a a b b
模式串S : a b a c a b
首先要明确前缀是除去字符串最后一个字符,头部字符的所有组合;后缀是除去字符串第一个字符,尾部字符的所有组合
列出模式串S所有的子串以及各个子串中包含的最大前后缀所包含的公共元素的长度:
0 a
0 a b
1 a b a
0 a b a c
1 a b a c a
0 a b a c a b
可根据上面列出的得出next数组(next值为公共元素长度向右移一格,初始值赋为-1):
模式串 : a b a c a b
next值 : -1 0 0 1 0 1
将模式串与文本串进行对比,若匹配失败则向右移动
eg:
文本串T:a b a c a a b a c a b a c a b a a b b
模式串S:a b a c a b
next值 :-1 0 0 1 0 1
当文本串中的a和模式串中的b不匹配时,则将模式串的索引变为失配出next数组的值,这里为1,再将索引为1的地方移到失配的地方。
重复以上步骤;

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void Next(string& needle,vector<int>& next) {
	next[0] = 0;
	int len = 0;
	int n = needle.size();
	int i = 1;
	while (i < n) {
		if (needle[i] == needle[len]) {
			++len;
			next[i] = len;
		}
		else {
			while (len > 0) {
				--len;
				if (needle[i] == needle[len]) {
					++len;
					next[i] = len;
					break;
				}
				next[i] = len;
			}

		}
		++i;
	}
}
void move_Next(vector<int>& next) { //将公共元素长度向右移一格,初始值赋为-1
	vector<int> temp;
	temp.push_back(-1);
	for (int i = 0; i < next.size() - 1; ++i) {
		temp.push_back(next[i]);
	}
	swap(next, temp);
}

int KMP(string& needle, string& mainStr, vector<int>& next) {
	int i = 0, j = 0;
	while (i < mainStr.size()){
		if (j == needle.size() - 1 && mainStr[i] == needle[j]) return i - j;
		if (mainStr[i] == needle[j]) {
			++i;
			++j;
		}
		else {
			j = next[j];
			if (j == -1 ) {
				++i;
				++j;
			}
		}
	}
	return -1;
}

int main() {
	string needle = "abacab";
	string mainStr = "abacaabacabacabaabb";
	int len = needle.size();
	vector<int> next;
	next.resize(len);
	Next(needle, next);
	move_Next(next);
	int res = KMP(needle, mainStr, next);
	
	cout << res << endl;
	system("pause");
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值