KMP算法是一種改進的字符串匹配算法
KMP的核心在於NEXT數組。
初始化next數組很巧妙,用next自己匹配自己,使得複雜的從m*m下降到m
求next數組和kmp匹配的函數有相似之處
暴力搜索複雜度m*n,KMP爲m+n,效率很不錯,不過在一些特定情況下kmp表現也會很糟糕,此處不做討論。
void init_next(char *t, int *next) {
int i = 0, j = -1;
next[i] = j;
int len = strlen(t);
while(i < len) {
if (j == -1 || t[i] == t[j]) {
next[++i] = ++j;
} else {
j = next[j];
}
}
}
int kmp(char *s, char *t, int *next) {
int lens = strlen(s), lent = strlen(t);
int i = 0, j = 0;
while(i < lens && j < lent) {
if(j == -1 || s[i] == t[j]) {
++i; ++j;
} else {
j = next[j];
}
}
if(j == lent) {
return i-lent;
} else {
return -1;
}
}