模式匹配算法的改进——KMP算法

来源:互联网 发布:淘宝运营计划怎么写 编辑:程序博客网 时间:2024/05/16 15:48
 
模式匹配算法的改进——KMP算法
 
      这种算法是D.E.Knuth 与V.R.Pratt和J.H.Morris同时发现的,因此人们称为KMP算法。此算法可以在O(n+m)的时间数量级上完成串的模式匹配操作。
      其基本思想是:每当匹配过程中出现字符串比较不等时,不需回溯i指针,而是利用已经得到的“部分匹配”结果将模式向右“滑动”尽可能远的一段距离后,继续进行比较。
      假设主串为“s1s2,...sn",模式串为”p1p2...pn",当主串中第i个字符与模式串中第j个字符“失配”(比较不等)时,主串第i字符(i指针不回溯)应与模式中哪个字符再比较?
      令当s[i]!=p[j]时,s[i]应与p[next[j]]进行比较。




      例如: P="abaabcac"

附:

KMP
算法查找串S中含串P的个数count
#i nclude <iostream>
#i nclude <stdlib.h>
#i nclude <vector>
using namespace std;

inline void NEXT(const string& T,vector<int>& next)
{
    //
按模式串生成vector,next(T.size())   
    next[0]=-1;            
    for(int i=1;i<T.size();i++ ){
        int j=next[i-1];
        while(T[i]!=T[j+1]&& j>=0 )
         j=next[j] ;  //
递推计算

        if(T[i]==T[j+1])next[i]=j+1; 
        else next[i]=0;  //
    }   

inline string::size_type COUNT_KMP(const string&  S,
                    const string&  T)
{
    //
利用模式串Tnext函数求T在主串S中的个数countKMP算法
    //
其中T非空,
    vector<int> next(T.size());
    NEXT(T,next);
    string::size_type index,count=0;   
    for(index=0;index<S.size();++index){      
        int pos=0;
        string::size_type iter=index;
        while(pos<T.size() && iter<S.size()){
            if(S[iter]==T[pos]){
                ++iter;++pos;
            }
            else{
                if(pos==0)++iter;              
                else pos=next[pos-1]+1;
            }   
        }//while end
        if(pos==T.size()&&(iter-index)==T.size())++count;
    } //for end
    return count;
}
int main(int argc, char *argv[])
{
    string S="abaabcacabaabcacabaabcacabaabcacabaabcac";
    string T="ab";
    string::size_type count=COUNT_KMP(S,T);
    cout<<count<<endl;
 
  system("PAUSE");
  return 0;


原创粉丝点击