理论参考:阮一峰老师http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; void BuildPatchMatchTable(int *partMatchTable, char *findstr) { int len = strlen(findstr); if (findstr == NULL) return; partMatchTable[0] = 0; string findstring = string(findstr); string tmpstr = ""; vector<string> prefixVec; vector<string> suffixVec; for (int i = 2; i < len+1; i++) { tmpstr = findstring.substr(0,i); //前缀: for (int j = 1; j < i; j++) prefixVec.push_back(tmpstr.substr(0, j)); //后缀: for (int j = 1; j < i; j++) suffixVec.push_back(tmpstr.substr(j)); //共有元素的最大长度 int maxsize = 0; for (int j = 0; j < prefixVec.size(); j++) { int length = 0; auto it = find(suffixVec.begin(), suffixVec.end(), prefixVec[j]); if (it != suffixVec.end()) length = prefixVec[j].size(); maxsize = max(length, maxsize); } partMatchTable[i - 1] = maxsize; prefixVec.clear(); suffixVec.clear(); } } int KMP(char *srcstr, char *findstr){ int len = strlen(findstr); int *partMatchTable = new int[len]; BuildPatchMatchTable(partMatchTable, findstr); int temp = strlen(srcstr) - strlen(findstr); int pos = 0; while (pos < temp) { int j = 0; for (int i = pos; i < (pos + len); i++) { if (srcstr[i] == findstr[i - pos]) { ++j; if (j == len) { delete partMatchTable; return pos; } } else { if (j == 0){ pos = pos + 1; } else { pos = pos + j- partMatchTable[j - 1]; } break; } } } delete partMatchTable; return -1; //不存在 } int _tmain(int argc, _TCHAR* argv[]) { char srcStr[] = "bbc abcdab abcdabcdabde"; char findStr[] = "abcdabd"; cout << "pos:" << KMP(srcStr, findStr) << endl; system("pause"); return 0; }
时间: 2024-10-23 23:56:25