###对于主串长度为m,模式串长度为n的匹配,使用KMP算法复杂度为O(m+n)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
//首先构建next矩阵,用于确定重新匹配时模式串开始的位置
void get_nextval(const char* ptrn, int plen, vector<int>& nextval)
{
int i = 0;
nextval[i] = -1;
int j = -1;
while (i < plen - 1)
{
if (j == -1 || ptrn[i] == ptrn[j])
{
++i;
++j;
nextval[i] = j;
}
else
{
j = nextval[j];
}
}
}
//核心算法,如果找到,返回主串中结束的位置,如果未找到,返回-1
int kmp_search(const char* src, int slen, const char* patn, int plen, vector<int>& nextval, int pos)
{
int i = pos;
int j = 0;
while (i < slen && j < plen)
{
if (j == -1 || src[i] == patn[j])
{
++i; ++j;
}
else
{
j = nextval[j];
}
}
if (j >= plen)
{
return i - plen;
}
else
{
return -1;
}
}
//测试用例
int main()
{
const char* src = "abcabbabcabcbab";
const char* patn = "abcabc";
//int* nextval = new int[strlen(patn)]();
vector<int> nextval(strlen(patn));
get_nextval(patn, strlen(patn), nextval);
kmp_search(src, strlen(src), patn, strlen(patn), nextval, 0);
return 0;
}