不知道看了几遍的kmp,反正到现在都没有弄清楚next[j]的计算和kmp的代码实现,温故而知新,经常回来看看,相信慢慢的就回了
/*!* \file KMP_算法.cpp** \author ranjiewen* \date 2017/02/12 16:12**/void preKmp(const char* pattern, int m, int kmpNext[]) //和GetNextval等价{ int i, j; i = 0; j = kmpNext[0] = -1; while (i-1 && pattern[i] != pattern[j]) // i为后缀,j为前缀 { j = kmpNext[j]; } i++; j++; if (pattern[i] == pattern[j]) { kmpNext[i] = kmpNext[j]; } else { kmpNext[i] = j; } }}#include using namespace std;#include void KMP(string p, string t){ int m = p.length(); int n = t.length(); if (m>n) { cerr << "Unsuccessful match!"; } const char* x = p.c_str(); const char* y = t.c_str(); int i = 0, j = 0, kmpNext[128]; preKmp(x, m, kmpNext); i = j = 0; while (i -1 && x[j] != y[i]) { j = kmpNext[j]; } j++; i++; if (j >= m) { cout << "Matching index found at:" << i - j << endl; j = kmpNext[j]; } }}int main(int argc, char** argv) { string p1 = "abcabcad"; string p2 = "adcadcad"; string p3 = "ababcaabc"; string t = "ctcabcabcadtcaabcabcadat"; cout << "KMP: " << endl; KMP(p1, t); // cout<<"KMP: "<
- 以后kmp算法都按照这样写
void GetNext(char* p, int next[]){ int pLen = strlen(p); next[0] = -1; int k = -1; int j = 0; while (j < pLen - 1) //j
有这样写的,else效果就是j==-1的时候
while (Text[i] != '\0' && Pattern[j] != '\0') { if (Text[i] == Pattern[j]) { ++i;// 继续比较后继字符 ++j; } else { index += j - next[j]; if (next[j] != -1) j = next[j];// 模式串向右移动 else { j = 0; ++i; } } }//while