vector<string> StringAlgorithms::kmp(vector<string> toCompare, string toSearch) { int num = 0; int m = toSearch.length(); vector<int> prefix(m); pre_kmp(toSearch, prefix); vector<string> ret; int n; for (int k = 0; k < toCompare.size(); k++) { n = toCompare[k].length(); int q = -1; for (int i = 0; i < n; i++) { while (q > -1 && toSearch[q + 1] != toCompare[k][i]) q = prefix[q]; if (toSearch[q + 1] == toCompare[k][i]) q++; if (q == m - 1) ret.push_back(toCompare[k]); } } return ret; }
int kmp(string text, string pattern) { int num=0; int m=pattern.length(); vector<int> prefix(m); pre_kmp(pattern, prefix); int n=text.length(); int q=-1; for (int i=0; i<n; i++) { while (q>-1 && pattern[q+1]!=text[i]) q=prefix[q]; if (pattern[q+1]==text[i]) q++; if (q==m-1) { //cout <<"pattern occurs with shift" << i-m+1 << endl; num++; q=prefix[q]; } } return num; }