1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include <iostream> #include <iterator> #include <vector> using namespace std;
void get_next(const string& pattern, vector<int>& next) { int n = pattern.length(); next[0] = -1; int i = 0, j = -1; while (i < n) { while (j >= 0 && pattern[i] != pattern[j]) j = next[j]; i++; j++; if (pattern[i] == pattern[j]) next[i] = next[j]; else next[i] = j; } }
vector<int> kmp(const string& str, const string& pattern, const vector<int>& next) { vector<int> ans; int n = str.length(); int m = pattern.length(); int i = 0, j = 0; while (i < n) { while (j >= 0 && str[i] != pattern[j]) j = next[j]; i++; j++; if (j == m) { ans.emplace_back(i - m); j = next[m]; } } return ans; } int main() { string str = "aabcd"; string pattern = "abab"; vector<int> next(pattern.length()); get_next(pattern, next); copy(next.begin(), next.end(), ostream_iterator<int>(cout, " "));
auto ans = kmp(str, pattern, next); copy(ans.begin(), ans.end(), ostream_iterator<int>(cout, " ")); }
|