对于KMP算法,最重要的是要把握其中的next数组的含义及求法
考虑一个模式字符串:b1b2...bn,定义next[s]如下:
next[s] is the longest proper prefix of b1b2...bs that is also a suffix of b1b2...bs
#include "kmp.h" #include <string.h> void makeNext(const char* patt, int* next){ int len = strlen(patt); //next must be an array with len + 1 element next[1] = 0; int s = 0; const char *p = patt - 1; for (int t = 1; t < len; t++){ while (s > 0 && p[t + 1] != p[s + 1]) s = next[s]; if (p[t + 1] == p[s + 1]){ s += 1; next[t + 1] = s; } else next[t + 1] = 0; } } int search(const char* src, const char* patt){ int pattLen = strlen(patt); int srcLen = strlen(src); int *next = new int[pattLen + 1]; memset(next, 0, (pattLen + 1) * sizeof(int)); makeNext(patt, next); int i = 0; int j = 0; int result = -1; for (i = 0; i < srcLen; i++){ while (j > 0 && src[i] != patt[j]) j = next[j]; if (src[i] == patt[j]) j++; if (j == pattLen){ result = i - pattLen + 1; break; } } return result; }