Boyer-Moore算法的一个C++版本

来源:互联网 发布:php九九乘法表加表格 编辑:程序博客网 时间:2024/06/05 20:05
#include <stdlib.h>#include <iostream>#define MAX(x,y) x>y?x:yusing namespace std;class Matcher{public:Matcher(){}~Matcher(){}bool isMatch(char* ori, char* sub){cout << ori << "<->" << sub << "  ";oriLen = strlen(ori);subLen = strlen(sub);originalString = ori;subString = sub;positionMap = new PositionMap(sub);int count = 0;cout << "[result : ";// start from the last of subfor (int i = subLen - 1; i < oriLen;){int inc = 0;if(checkNext(i, inc)){cout << i << ',';count ++;}i+=inc;}delete positionMap;bool match = count != 0;cout <<"] total : " << count << endl;return match;}private:class PositionMap{private:int **hashMap;int *positionMap;int size;void add(char c, int position){int *pMap = hashMap[c];int length = pMap[0];pMap[length + 1] = position;pMap[0] = length + 1;}public:PositionMap(char* sub){size = strlen(sub);hashMap = new int*[128];for(int i = 0; i < 128; i++){hashMap[i] = new int[size];memset(hashMap[i], -1, sizeof(int) * size);hashMap[i][0] = 0;}for (int i = 0; i < size; i++){add(sub[i], i);}}~PositionMap(){for (int i = 0; i < size; i++){delete[] hashMap[i];}delete[] hashMap;}int getDupl(char c, int index){int *pRow = hashMap[c];int length = pRow[0];for (int i = length; i > 0; i--){if(pRow[i] <index)return pRow[i];}return -1;}};char* originalString;char* subString;int oriLen,subLen;PositionMap* positionMap;bool checkNext(int i, int &increase){char *ori= originalString, *sub = subString;int index = 0;bool hasGood = false;int end = subLen - 1;for (int j = end; j >= 0; j--){char o = ori[i - index++];char s = sub[j];if(o != s){int incGood = -1,incBad = -1;// are o and s matched last time?if(hasGood){incGood = end - positionMap->getDupl(sub[end], end);}else{incBad = j - positionMap->getDupl(o, j);}increase = MAX(incGood, incBad);return false;}else{hasGood = true;}}increase = subLen;return true;}};

测试用:

#include "BMMatcher.hpp"int main(char* argv){Matcher m;m.isMatch("awataa","wat");m.isMatch("here is a simple example","ample");m.isMatch("here is a simple example","example");m.isMatch("AAAABAAAABAAABAAA","AB");m.isMatch("awaaaaaaaawrwatawt","awrwatawt");system("pause");}



其他资源:

算法解释(简单易懂,还有配图):http://kb.cnblogs.com/page/176945/

算法详解和C++实现:http://www.cnblogs.com/Seiyagoo/p/3352598.html

0 0
原创粉丝点击