KMP算法是一种时间复杂度为O(m+n)的字符串匹配算法,其中m和n分别为模式串和文本串的长度。其主要思想是利用已匹配到的前缀信息,避免在匹配过程中重复地搜索已经比较过的字符。具体实现需要用到getNext函数来求出模式串的next数组,kmp_search函数用于搜索模式串在文本串中的位置,并返回匹配的位置下标。
// KMP算法模板
void get_next(const string& pattern, vector<int>& next) {
int len = pattern.size();
int j = 0;
next[0] = next[1] = 0;
for (int i = 1; i < len; ++i) {
while (j > 0 && pattern[i] != pattern[j]) {
j = next[j];
}
if (pattern[i] == pattern[j]) {
++j;
}
next[i+1] = j;
}
}
vector<int> kmp_search(const string& text, const string& pattern) {
int n = text.size(), m = pattern.size();
vector<int> next(m+1);
get_next(pattern, next);
int j = 0;
vector<int> res;
for (int i = 0; i < n; ++i) {
while (j > 0 && text[i] != pattern[j]) {
j = next[j];
}
if (text[i] == pattern[j]) {
++j;
}
if (j == m) {
res.push_back(i-m+1);
j = next[j];
}
}
return res;
}