KMP字符串匹配算法 - 王陸 - 博客园 (cnblogs.com)
int nxt[100];
获得nxt数组(nxt[j]表示当匹配到j失败是跳转到nxt[j]位置)
int j = 0, k = -1, len = s.length(); nxt[0] = -1; while (j < len) { if (k == -1 || s[j] == s[k]) { j++; k++; nxt[j] = k; } else k = nxt[k]; }
KMP主代码:
int KMP() { string p = "abcadabcabd"; string s = "abcabd"; int lens = s.length(); int lenp = p.length(); int i = 0, j = 0; while (i < lenp && j < lens) { if (j == -1 || p[i] == s[j]) { i++; j++; } else j = nxt[j]; } if (j == lens) { cout << "Yes"; } else { cout << "No"; } return 0; }