大神代码:https://blog.csdn.net/v_july_v/article/details/7041827
本篇是接着上一篇的理论写了一个简单的Demo,上面的链接是代码的原地址,下面是我写的Demo,供大家参考。
2. 匹配函数
int KMPSearch(char* a,char* p,int * next){
int a_len = strlen(a);
int p_len = strlen(p);
int i=0, j=0;
while (i < a_len&&j < p_len){
if (j >= 0){
cout << "after : a[i] is : " << a[i] << ", p[j] is : " << p[j] << ", i is : " << i << ", j is : " << j << endl;
}else{
cout << "after : a[i] is : " << a[i] << ", p[j] is : ** " << ", i is : " << i << ", j is : " << j << endl;
}
if (j == -1 || a[i] == p[j]){
++i;
++j;
}
else
{
j = next[j];
}
}
if (j == p_len){
return i - j;
}
else{
return -1;
}
}
下面是程序汇总
#include "stdafx.h"
#include "iostream"
using namespace std;
void Next(char * a,int * next){
int n = strlen(a);
next[0] = -1;
int k = -1;
int j = 0;
while (j<n-1){
//cout << "befor :a is : " << a << ", next[k] is : " << next[k] << ", j is : " << j << ", K is : " << k << endl;
if (k == -1 || a[j] == a[k]){
++k;
++j;
//next[j] = k;
if (a[j] != a[k])
next[j] = k;
else{
next[j] = next[k];
}
}
else
{
k = next[k];
}
//cout << "after :a is : " << a << ", next[k] is : " << next[k] << ", j is : " << j << ", K is : " << k << endl;
}
}
int KMPSearch(char* a,char* p,int * next){
int a_len = strlen(a);
int p_len = strlen(p);
int i=0, j=0;
while (i < a_len&&j < p_len){
if (j >= 0){
cout << "after : a[i] is : " << a[i] << ", p[j] is : " << p[j] << ", i is : " << i << ", j is : " << j << endl;
}else{
cout << "after : a[i] is : " << a[i] << ", p[j] is : ** " << ", i is : " << i << ", j is : " << j << endl;
}
if (j == -1 || a[i] == p[j]){
++i;
++j;
}
else
{
j = next[j];
}
}
if (j == p_len){
return i - j;
}
else{
return -1;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char a[] = "abab";
char p[] = "abacabayabab";
int n = strlen(a);
int next[4] = { -2};
Next(a,next);
int Pos = KMPSearch(p, a, next);
return 0;
}