以前写的代码,先搬运到CSDN上来。先贴代码,后面补说明
代码实现
KMP主函数
int KMP(char * t, char * p) { int i = 0; int j = 0; int* pNext = new int[(int)strlen(p)]{-1}; GetNext(p,pNext); while (i < (int)strlen(t) && j < (int)strlen(p)) { if (j == -1 || t[i] == p[j]) { i++; j++; } else j = pNext[j]; } if (j == strlen(p)) return i - j; else return -1; }
GetNext函数
void GetNext(char * p, int * next) { next[0] = -1; int i = 0, j = -1; while (i < (int)strlen(p)) { if (j == -1 || p[i] == p[j]) { ++i; ++j; next[i] = j; } else j = next[j]; } }