#include <iostream> #include <string> #include <vector>using namespace std; void Next (const string & pat,vector<int> & Next) {next.resize (Pat.length ()); if (pat.length () = = 0) return; Next[0] = -1;for (size_t pos = 1; pos < Pat.length (); ++pos) {size_t Sublen = pos-1;while (sublen >= 0) {if (Pat.substr (0 , sublen) = = Pat.substr (pos-sublen+1, Sublen)) Break;--sublen;} Next[pos] = Sublen;} return;} int main (void) {string str1, Str2;while (cin >> str1 >> str2) {vector<int> next; Next (str2, next);vector<int> pos;int i = 0, J1 = 0, J2 = 0;while (J1 < Str1.length ()) {J2 = j1-i;if (J2 >= str 2.length ()) {//Foundpos.push_back (i);//move On;int delta = str2.length (); i = i + delta;j1 = max (i,j1);} else if (str1[j1] = = Str2[j2]) {++j1;} else {//str1[j1]! = Str2[j2];int Delta = j2-next[j2];i = i + delta;j1 = max (i,j1);}} Output.cout << "Str1.length ():" << str1.length () << endl;cout << "Str2.length ():" << str 2.length ()<< endl;cout << "str1 from Pos:" << endl;for (int i = 0; I < pos.size (); ++i) cout << "[" << (i+1) << "]:" << str1.substr (Pos[i], string::npos) << endl;cout << ; "STR2:" << str2 << Endl;} return 0;}
Reference from: http://www.cnblogs.com/BeyondAnyTime/archive/2012/07/09/2583133.html
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + implementation of KMP pattern matching algorithm