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
| struct KMP { std::string S, T; int s_len, t_len; std::vector<int> ne; std::vector<int> pos; KMP() {} KMP(std::string& s, std::string& t) { init(s, t); }
void init(std::string& s, std::string& t) { S = s; T = t; s_len = S.size(); t_len = T.size(); ne.resize(t_len, 0); pos.clear(); }
void get_next() { ne[0] = 0; for (int i = 1, j = 0; i < t_len; i++) { while (j && T[j] != T[i]) { j = ne[j - 1]; } if (!j && T[j] != T[i]) { continue; } j ++ ; ne[i] = j; } }
void get_pos() { get_next(); for (int i = 0, j = 0; i < S.size(); i++) { while (j && S[i] != T[j]) { j = ne[j - 1]; } if (!j && S[i] != T[j]) { continue; } j ++ ; if (j == t_len) { pos.push_back(i - j + 1); j = ne[j - 1]; } } }
};
|