BM(Boyer-Moore)字符串匹配算法的实现(一种有效常用的字符串匹配算法)

除了已知的KMP模式匹配算法外,还有一种比较常用的匹配算法BM算法(Boyer-Moore)字符串匹配算法

 

【算法的C++实现如下】:

 

 /******************************************************************* * * DESCRIPTION:Boyer-Moore Algorithm for String (BM Algorithm) * * AUTHOR:NeeSky * * DATE:2009-9-10 * *******************************************************************/ /** include files **/ #include <iostream> using namespace std; /** * * Compare Two string from Tail, and return the max commo chars * * @author NeeSky (2009-9-14) * * @param strSample :Given Sample string * @param tail : tail position of strSample * @param strTemplate :Given template string * * @return int : the max common chars length */ int CommonChars_fromTailStart(const string& strSample,int tail,const string strTemplate ) { assert(tail<strSample.length()&&strSample.length()>=strTemplate.length());/*Proper Parameters List*/ int i;/*How many chars matched from tail*/ for(i=0;i<strTemplate.length();++i) { if(strSample[tail-i]!=strTemplate[strTemplate.length()-i-1]) break; } return i; } /** * BM String Match Core Algorithm[Letter Case Sense] * * @author NeeSky (2009-9-13) * * @param strSample: Sample String * @param strTemplate: Template String * * @return int : first char position of string matched(start 0) */ int BM_StringMatch(const string& strSample,const string& strTemplate) { if(strTemplate==""||(strTemplate.length()>strSample.length()))return -1;/*Not Exist in strSample*/ int lenTemplate=strTemplate.length(),lenSample=strSample.length(); int tail=lenTemplate-1;/*init the start and tail position*/ while(tail<lenSample) { int numSameChars=CommonChars_fromTailStart(strSample,tail,strTemplate); if(numSameChars==lenTemplate) return tail-lenTemplate+1;/*The First Match Position*/ if(numSameChars==0) ++numSameChars;/*Just Jump One Position*/ tail+=numSameChars;/*Jump numSameChars Position*/ } return -1;/*Not Match in Sample String*/ } /** * Output the Problem info. ,just call BM_StringMatch function * * @author NeeSky (2009-9-14) * * @param strSample: Sample String * @param strTemplate: Sample String */ void SolveProblemOutput(const string strSample,const string strTemplate) { cout<<"Sample String: "<<strSample<<"; Template String:"<<strTemplate<<";"<<endl; int pos=BM_StringMatch(strSample,strTemplate); if(pos==-1) cout<<"Sorry,No Match!"<<endl<<endl; else cout<<"Match Pos: "<<pos<<endl<<endl; return; } /** * For Boyer-Moore String Algorithm, A effective algorithm * * @author NeeSky (2009-9-10) * * @return int */ int main(void) { /*Testing Cases*/ SolveProblemOutput("a simple example","example"); SolveProblemOutput("My Happiness is your happiness","happiness"); SolveProblemOutput("My Happinessis is your happiness"," is"); return 0; }

 

 

【输出】

 

 

 

【下面是转自http://vimory.javaeye.com/blog/199656 的BM算法的图解过程,稍后做出C++的实现

 

 BM(Boyer-Moore)字符串匹配算法的实现(一种有效常用的字符串匹配算法)_第1张图片

 

 

你可能感兴趣的:(BM(Boyer-Moore)字符串匹配算法的实现(一种有效常用的字符串匹配算法))