void T2DSingleTemplateMatcher::FindRowMatchSequence(const std::vector<size_t>& Matches, size_t columnnumber, TMatchResults &Result, const std::vector<size_t>& equivalences) { std::vector<size_t> prefix_function(Matches.size(),0); if (!Matches.empty()) if (Matches[0] == 0) { prefix_function[0]=1; if (templateheight == 1) Result.push_back(std::make_pair(0,columnnumber)); } for (size_t rownumber = 1; rownumber < textheight; ++rownumber) { size_t prev = prefix_function[rownumber - 1]; if (Matches[rownumber] != equivalences[prev]) prev = 0; prefix_function[rownumber] = prev; if (Matches[rownumber]==equivalences[prev]) ++prefix_function[rownumber]; if (prefix_function[rownumber] == templateheight) Result.push_back(std::make_pair(rownumber, columnnumber)); } }
void kmp(char *string, char *substring) { int n = strlen(string); int m = strlen(substring); int q = -1; int *pi; pi = prefix_function(substring); for (int i = 0; i < n; i++) { while ((q > -1) && (substring[q+1] != string[i])) q = pi[q]; if (substring[q+1] == string[i]) q++; if (q == m-1) { printf("The substring appears at position %i.\n", i-m+1); q = pi[q]; } } }
//returns all positions of matched in given text vector<int> kmp(string text, string pattern) { vector<int> pre(pattern.size()); vector<int> ans; if (pattern.size() == 0) return ans; prefix_function(pre, pattern); int j = -1; //Complexity is O(n) for (int i=0 ; i<text.size(); ++i) { while (j>=0 && text[i]!=pattern[j + 1]) { j = pre[j]; } if (text[i] == pattern[j + 1]) { j++; if (j+1 == pattern.size()) { ans.push_back(i - j); j = pre[j]; } } } return ans; }