#include <iostream>
#include <string>
using namespace std;
void GetNext(string P, int next[])
{
int p_len = P.size();
int i = 0;
int j = -1;
next[0] = -1;
while (i < p_len - 1)
{
if (j == -1 || P[i] == P[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
int KMP(string S, string P, int next[])
{
GetNext(P, next);
int i = 0;
int j = 0;
int s_len = S.size();
int p_len = P.size();
while (i < s_len && j < p_len)
{
if (j == -1 || S[i] == P[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j == p_len)
return i - j;
return -1;
}
int main()
{
int next[100] = { 0 };
cout << KMP("bbc abcdab abcdabcdabde", "abcdabd", next) << endl;
return 0;
}
- 如果之前有了解过KMP算法,那么 看懂KMP这个函数的实现没有什么问题。
- 这里难点在GetNext函数的理解上面,说它难,其实也不难,主要是它也采用了kmp的思想来生成next数组。