KMP算法
KMP算法指的是字符串模式匹配算法,问题是:在主串T中找到第一次出现完整子串P时的起始位置。该算法是三位大牛:D.E.Knuth、J.H.Morris和V.R.Pratt同时发现的,以其名字首字母命名。
下面是KMP算法的C++版本:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//getNext
vector<int> getNext(string str2)
{
if (str2.length() == 1) {
vector<int> next{ -1 };
return next;
}
vector<int> next(str2.length());
next[0] = -1; next[1] = 0;
int i = 2; //当前来到的位置
int cn = 0; //比对的位置,要与i-1位置相比
while (i < str2.length())
{
if (str2[i - 1] == str2[cn]) //配上了
next[i++] = ++cn;
else if (cn > 0) //没配上,cn还可以往前跳
cn = next[cn];
else //没配上,cn已经跳到了0位置
next[i++] = 0;
}
return next;
}
int KMP(string str1, string str2)
{
if (str2.length() < 1 || str1.length() < str2.length())
return -1;
int i1 = 0;//str1比对位置
int i2 = 0;//str2比对位置
vector<int> next = getNext(str2);
while (i1 <str1.length() && i2 < str2.length())
{
if (str1[i1] == str2[i2]) //相等共同往下动
{
i1++;
i2++;
}
else if (next[i2] == -1) //i2跳到了str2[0]
i1++;
else //如果不匹配,i2跳到下一寻找位置
i2 = next[i2];
}
//返回起始位置
return i2 == str2.length() ? i1 - i2 : -1;
}
int main()
{
string str1 = "ABCCABCCABCCABCCDEFGH";
string str2 = "CCDE";
cout << KMP(str1, str2) << endl;
system("pause");
return 0;
}