#include <vector>
#include <string>
std::vector<int> kmp_search(const std::string& s, const std::string& p) {
int n = s.length(), m = p.length();
std::vector<int> next(m, 0), positions;
// 构建next数组
for (int i = 1, len = 0; i < m;) {
if (p[i] == p[len]) {
next[i++] = ++len;
} else if (len) {
len = next[len - 1];
} else {
next[i++] = 0;
}
}
// KMP搜索
for (int i = 0, j = 0; i < n;) {
if (p[j] == s[i]) {
i++, j++;
}
if (j == m) {
positions.push_back(i - j);
j = next[j - 1];
} else if (i < n && p[j] != s[i]) {
if (j != 0) {
j = next[j - 1];
} else {
i++;
}
}
}
return positions;
}
算法复习8.1kmp
最新推荐文章于 2024-05-20 20:08:58 发布