#include <cstdlib> #include <iostream> #include <string> #include <vector> using namespace std; void getTab(string pat, vector<int> &vec) { int patLen = pat.size(); vec.push_back(-1); for(int i=1; i<patLen; i++) { int index = vec[i - 1]; while(pat[i] != pat[index + 1] && index >= 0) index = vec[index]; if(pat[i] == pat[index + 1]) vec.push_back(index + 1); else vec.push_back(-1); } } int find(string target, string pat) { vector<int> fTab; getTab(pat, fTab); int tarLen = target.size(); int patLen = pat.size(); int tarPos = 0, patPos = 0; while(tarPos < tarLen && patPos < patLen) { if(target[tarPos] == pat[patPos]) { tarPos++; patPos++; } else if(patPos == 0) tarPos++; else patPos = fTab[patPos - 1] + 1; } if(patPos < patLen) return -1; else return tarPos - patLen; } int main(int argc, char *argv[]) { string target, pat; cout << "please input the target string: " << endl; cin >> target; cout << "please input the patten string: " << endl; cin >> pat; int pos = find(target, pat); if(pos >= 0) cout << "find and pos is: " << pos << endl; else cout << "not found" << endl; system("PAUSE"); return EXIT_SUCCESS; }