定义:
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;
}