KMP算法
KMP算法
class KMP { public: vector<int> create_prefix_function(string s) { vector<int> next(s.size(), 0); next[0] = 0; int k = 0; for (int q = 1; q < s.size(); q++) { while (k > 0 && (s[k] != s[q])) { k = next[k - 1]; } if (s[k] == s[q]) { k = k + 1; } next[q] = k; } return next; } vector<int> match(string text, string query) { vector<int> next = create_prefix_function(query); vector<int> result; int q = 0; for (int i = 0; i < text.size(); i++) { while (q > 0 && (query[q] != text[i])) { q = next[q - 1]; } if (query[q] == text[i]) { q = q + 1; } if (q == query.size() - 1) { result.push_back(i - q + 1); q = next[q]; } } return result; } }; int main(int argc, char **argv) { KMP kmp; string text = "abababacaba"; string query = "ababaca"; vector<int> result = kmp.match(text, query); getchar(); return 0; }
最后的结果为2,表示从text索引2开始匹配