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
| vector<int> getNext(const string& p) { int n = p.size(); vector<int> next(n); next[0] = -1; int i = 0, j = -1; while (i < n - 1) { if (j == -1 || p[i] == p[j]) { ++i, ++j; if (p[i] == p[j]) next[i] = next[j]; else next[i] = j; } else { j = next[j]; } } return next; }
int KMP(const string& t, const string& p) { vector<int> next = getNext(p); int n = t.size(), m = p.size(); int i = 0, j = 0; while (i < n && j < m) { if (j == -1 || t[i] == p[j]) { ++i; ++j; } else { j = next[j]; } } if (j == p.size()) return i - j; else return -1; }
|