后续更新算法的详细步骤以及手算方法!!
头和存储表示
#include<cstdio>
#include<cstdlib>
#define Status int
typedef struct {
char* chr;
int length;
}SString;
nextval算法
void get_nextval(SString T, int nextval[]) {
int i, j = 0;
nextval[1] = 0;
while (i < T.length) {
if (j == 0 || T.chr[i] == T.chr[j]) {
++i; ++j;
if (T.chr[i] != T.chr[j]) {
nextval[i] = j;
}
else {
nextval[i] = nextval[j];
}
}
else {
j = nextval[j];
}
}
}
KMP算法
Status Index_KMP(SString S, SString T, int nextval[]) {
int i, j = 1;
get_nextval(T, nextval);
while (i < S.length && i < T.length) {
if (j == 0 || S.chr[i] == T.chr[i]) {
++i; ++j;
}
else {
j = nextval[j];
}
if (j > T.length) {
return i - T.length;//匹配成功
}
else {
return 0;
}
}
}