KMP算法实现

next数组用于存储模式串中元素为j位置的最大重叠度。

//KMP算法实现字符串匹配 
//
#include <cstdlib>
#include <iostream>

using namespace std;
 
 void compute_next(int* next,char const*p,int len){
      int j=0;
      int q=next[0]=-1;
      --len;
      while(j<len)
      if(q==-1||p[q]==p[j])
      next[++j]=++q;
      else 
      q=next[q];
      } 

char const* kmp_find(char const*t,int tlen,char const*p,int plen,int const*next){
      int i=-1;
      int j=-1;
      while((i<tlen)&&(j<plen)){
        if((j==-1)||(t[i]==p[j])) {++i;++j;}
        else j=next[j];                        
                                }
      if(j==plen) return t+i-plen;
      else return 0;                               
                                      }
 
int main()
{   char a[100]="ahgdhjggabcabcabbacll";
    char b[12]="abcabcabbac";
    char const* t_;
    int next[11];
    compute_next(next,b,11);
    for(int i=0;i<11;i++)
          cout<<next[i]<<endl;
          
    t_=kmp_find(a,100,b,11,next);
   if(!t_)
      cout<<"can not find mode string in target string!"<<endl;
      else 
      cout<<"the position of mode string in target string is:"<<t_-a+1<<endl;
    system("PAUSE");
    return EXIT_SUCCESS;
}

 

posted @ 2015-07-20 18:27  尾巴草  阅读(153)  评论(0编辑  收藏  举报