左神KMP算法 笔记
预处理阶段:创建部分匹配表。
搜索阶段:在文本中搜索模式。
匹配或失败:
next加速过程
加速核心
图解前面一定匹配不出
整体过程
代码
vector nextArray(const string& s) {
int m = s.size();
vector ne(m, 0);
ne[0] = -1;
if (m == 1)
return ne;
ne[1] = 0;
int i = 2, cn = 0;
while (i < m) {
if (s[i - 1] == s[cn])
ne[i++] = ++cn;
else if (cn > 0)
cn = ne[cn];
else
ne[i++] = 0;
return ne;
}
}
int kmp(const string& s1, const string& s2) {
int n = s1.size();
int m = s2.size();
vector ne= nextArray(s2);
int x = 0, y = 0;
while (x < n && y < n) {
if (s1[x] == s2[y]) {
x++;
y++;
}
else if (y == 0) {
x++;
}
else {
y = ne[y];
}
return y == m ? x - y : -1;
}
}