KMP matching

#include <iostream> #include <string> using namespace std ; struct KeyWord { string strkey ; int *matcher ; } ; void KMP_prefix(KeyWord &kw) ; bool KMP_matcher(string &s, KeyWord &t) ; int main() { string s = "12ababc5677" ; KeyWord t ; t.strkey = "77" ; if (KMP_matcher(s, t)) { cout << "SUCCESS" << endl ; } return 0 ; } void KMP_prefix(KeyWord &key) { int len = key.strkey.size() ; key.matcher = new int[len] ; key.matcher[0] = 0 ; int k = -1, q ; for (q = 1; q < len; ++q) { while ((k >= 0) && (key.strkey[k+1] != key.strkey[q])) { k = key.matcher[k] - 1 ; } if (key.strkey[k+1] == key.strkey[q]) { ++k ; } key.matcher[q] = k+1 ; } } bool KMP_matcher(string &s, KeyWord &t) { int n = s.size() ; int m = t.strkey.size() ; KMP_prefix(t) ; int q = -1, i ; for (i = 0; i < n; ++i) { while ((q >= 0) && (t.strkey[q+1] != s[i])) { q = t.matcher[q] - 1 ; } if (t.strkey[q+1] == s[i]) { ++q ; } if (q+1 == m) { return true ; } } return false ; }

你可能感兴趣的:(KMP matching)