前缀函数和KMP
KMP
https://oi-wiki.org/string/kmp/
vector<int> get_prefix(string s) {
int n = s.size();
vector<int> res(n, 0);
for (int i = 1; i < n; i++) {
int j = res[i - 1];
while (j > 0 && s[i] != s[j]) j = res[j - 1];
if (s[i] == s[j]) j++;
res[i] = j;
}
return res;
}
vector<int> kmp(string s, string t) {
string cur = t + "#" + s;
int n = s.size(), m = t.size();
vector<int> p = get_prefix(cur);
vector<int> res;
for (int i = m; i <= n + m; i++) if (p[i] == m) res.emplace_back(i - m * 2);
return res;
}
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果