Files
algorithm-template/trick/knuth-morris-pratt.cpp

29 lines
567 B
C++

#include <vector>
#include <string>
int knuth_morris_pratt(const std::string text, const std::string pattern) {
int n = text.length(), m = pattern.length();
std::vector<int> next(m, 0);
for (int i = 1, j = 0; i < m; i++) {
while (j > 0 && pattern[i] != pattern[j]) {
j = next[j - 1];
}
if (pattern[i] == pattern[j]) {
j++;
}
next[i] = j;
}
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && text[i] != pattern[j]) {
j = next[j - 1];
}
if (text[i] == pattern[j]) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}