码迷,mamicode.com
首页 > 其他好文 > 详细

KMP 字符串匹配

时间:2015-05-16 01:23:27      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:


理论参考:阮一峰老师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; }

 

KMP 字符串匹配

标签:

原文地址:http://www.cnblogs.com/wxquare/p/4507208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!