之前在看KMP算法~ 一头雾水 在百度查了半天资料~不是文字太多就是讲解复杂~
最终对于KMP算法的理解是看到阮一峰的 一篇文章才得以理解~
文章链接~字符串匹配的KMP算法
里边图文并茂的讲解了KMP算法的原理~但是里边并没有给出具体的算法~ 网上的算法文章也写得很难懂~ 各种公式~ 最后终于在大维基百科的帮助下理解了KMP的算法~
它里边的伪代码写得很清楚~(维基百科 KMP)配合着看应该很容易理解~
代码:
#include <iostream>
using namespace std;
void MakeNext(char *a, int* &next)
{
int len = strlen(a);
next = new int[len];
next[0] = -1;
next[1] = 0;
int count = 0;
for (int pos = 2; pos < len; )
{
if (a[pos-1] == a[count])
{
count++;
next[pos] = count;
pos++;
}
else if ( count > 0 )
{
count = next[count];
}
else
{
next[pos] = 0;
pos++;
}
}
}
int KmpSearch(char* a,char *s,int *next)
{
int len = strlen(a);
int lenS = strlen(s);
int m = 0;
int i = 0;
while ( (m+i) < len && i < lenS )
{
if (a[m+i] == s[i])
{
i++;
}
else if(next[i] < 0)
{
m++;
i = 0;
}
else
{
m = m + i - next[i];
i = next[i];
}
}
if ( i >= lenS )
return m;
return -1;
}
int main(int argc, char** argv) {
char a[] = "PARTICIPATE IN PARACHUTE";
char s[] = "ACHUT";
int *next;
MakeNext(s,next);
int k = KmpSearch(a,s,next);
delete []next;
return 0;
}