KMP算法
KMP算法学习视频
KMP算法程序实例如下
语言:C/C++
编译运行环境:
Visual Studio 2019
Code:blocks
#include <iostream>
#include <stdlib.h>
#include <cstring>
using namespace std;
typedef struct {
char* ch;
int length;
}Str;
//未改进的KMP算法代码实现
void get_next(Str substr, int* next)
{
int i = 0, j = -1; // i为后缀,j为前缀
next[0] = -1;
while (i < substr.length -1) {
if (j == -1 || substr.ch[i] == substr.ch[j]) {
i++;
j++;
next[i] = j;
}
else {
j = next[j];
}
}
}
int KMP(Str str, Str substr, int* next)//利用KMP算法匹配
{
int i = 0;
int j = 0;
while (i <= str.length && j < substr.length) {
if (j == -1 || str.ch[i] == substr.ch[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
if (j == substr.length)
return i - substr.length;
else
return -1;
}
int main(){
char a[] = "bacbababadababacambabacaddababacasdsd";
char b[] = "ababaca";
Str S, T;
S.length = strlen(a);
T.length = strlen(b);
int next[7] = {0,0,0,0,0,0,0};
S.ch = (char*)malloc(strlen(a) * sizeof(char));
T.ch = (char*)malloc(strlen(b) * sizeof(char));
S.ch = a;
T.ch = b;
get_next(T, next);
for (int i = 0; i < 7; i++) {
cout << next[i] << " ";
}
cout << endl;
cout << KMP(S, T, next);
return 0;
}
该算法的难点是如何得到next[]数组,是KMP算法的关键,也是它最巧妙的地方。
get_next()函数算法的思想是"用自己匹配自己",根据next[0],next[1],…,next[i-1]递推next[i],代码和KMP()函数匹配部分非常相似。
学习心得
通过视频学习可以有一个大概的理解,如有不理解的地方还是得通过运行程序,设置断点调试才能有比较清晰得理解。