int computeMaxPalindrome(string& text, string& pattern) { vector<int> prefix = computePrefixFunction(pattern); int k = -1; int max = -1; for (int i = 0; i < text.size(); ++ i) { while (k >= 0 && text[i] != pattern[k + 1]) { k = prefix[k]; } if (text[i] == pattern[k + 1]) { ++ k; if (k > max) max = k; } if (k + 1 == pattern.size()) { return k + 1; } } return max + 1; }
//---------------------------------------------------------------------------------------- void KMPStringMatcher::findMatches(const string& t, const string& p, vector<int> & rShift) { cout << "Text string : " << t << endl; cout << "Pattern string: " << p << endl; vector<int> PI; computePrefixFunction(p, PI); //Number of characters matched int q = 0; //Scan text from left to right for(int i = 1; i <= t.size(); ++i) { //Next character does not match while(q > 0 && p.at(q) != t.at(i - 1)) q = PI[q - 1]; //Next character matches if(p.at(q) == t.at(i - 1)) ++q; //Is all of p matched? if(q == p.size()) { //Record the shift at which the pattern matches rShift.push_back(i - p.size()); q = PI[q - 1]; } } }
int main(){ freopen("strmatch.in", "r", stdin); freopen("strmatch.out", "w", stdout); int m, n; fgets(a + 1, NMAX, stdin); fgets(b + 1, NMAX, stdin); a[0] = ' '; b[0] = ' '; // search a substring into b m = strlen(a) - 2; // get rid of newline n = strlen(b) - 2; // get rid of \n int i; for(i = 1; i <= m; ++i){ if(!((a[i] >='a' && a[i] <= 'z') || (a[i] >= 'A' && a[i] <= 'Z') || (a[i] >= '0' && a[i] <= '9'))) break; } m = i - 1; a[i] = 0; for(i = 1; i <= n; ++i){ if(!((b[i] >='a' && b[i] <= 'z') || (b[i] >= 'A' && b[i] <= 'Z') || (b[i] >= '0' && b[i] <= '9'))) break; } n = i - 1; b[i] = 0; computePrefixFunction(a, pi, m); // kmp int matchCount = 0; int q = 0; // number of characters matched for(int i = 1; i <= n; i++){ while ( q > 0 && a[q + 1] != b[i]){ // next character does not match q = pi[q]; } if (a[q + 1] == b[i]) ++q; if (q == m){ q = pi[q]; // look for next match matchCount++; if(matchCount <= 1000) matches[matchCount] = i - m; } } // print matches printf("%d\n", matchCount); for(int i = 1; i <= MIN(matchCount, 1000); ++i){ printf("%d ", matches[i]); } putchar('\n'); return 0; }