分为两个操作:
1.求next数组/longestPrefix数组
2.kmp字符串匹配
模板:
cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int> computePrefix(string pat) {
int m = pat.size();
vector<int> longestPrefix(m);
for(int i = 1, k = 0; i < m; i ++ ) {
while(k > 0 && pat[i] != pat[k]) {
k = longestPrefix[k - 1];
}
if(pat[i] == pat[k]) {
longestPrefix[i] = ++k;
}
else {
longestPrefix[i] = k;
}
}
return longestPrefix;
}
void kmp(string text, string pat) {
int n = text.size();
int m = pat.size();
vector<int> longestPrefix = computePrefix(pat);
for(int i = 0, k = 0; i < n; i ++ ) {
while(k > 0 && pat[k] != text[i]) {
k = longestPrefix[k - 1];
}
if(pat[k] == text[i]) {
k ++;
}
if(k == m) {
cout << i - m + 1 + 1 << endl;
k = longestPrefix[k - 1];
}
}
}
int main() {
string text, pat;
cin >> text >> pat;
kmp(text, pat);
return 0;
}