[导入]KMP算法

呵呵以前竞赛的时候老师都不愿讲的一种算法,据说非常难,今天发现了一个C++版的,贴出来.

 

#include<iostream>
#include
<time.h>
#include
<string>
using namespace std;
void init(string ,string);
void show(char [],int);
int kmp(string ,string,int pos);
void get_next(char*,int *);
string s1,t1;
int m,n;
char *s;
char *t;
int *next;
/*************************MAIN**************************************/
int main(int argc[],char*args[])
{
    
 
double t=clock();
 cout
<<"找到位置为:"<<kmp("acbsabcaacabaabaabcacaabc","abaabca",1)<<endl;
    delete[] s;
 delete[] next;
 cout
<<"耗时:"<<(clock()-t)/1000<<"毫秒!"<<endl;
 
return 0;
}
   
/**********************++++NEXT++++********************************/
void get_next(char s[],int ne[])
{
    ne 
=new int[n+1];
    next
=new int[n+1];
    ne[
0]=9999;
    
int i(1),j(0);
    ne[
1]=0;
    
while(i<=(int)(t[0]))//数组是字符型的,要转化为整数
 {
     
if(j==0||t[i]==t[j]){++i;++j;ne[i]=j;}
     
else j=ne[j];
 }

   
for( i=1;i<=n;i++)
   
{
   cout
<<"next["<<i<<"]="<<ne[i]<<endl;
      next[i]
=ne[i];
   }

}

/********************++++KMP+++**********************************/
  
int kmp(string s0,string t0,int pos)
  
{
        init(s0,t0);
        
int i=pos,j=1;
        
while(i<=((int)(s[0]))&&(j<=((int)(t[0]))))
  
{
         
if((j==0)||(s[i]==t[j])){++i;++j;}
      
else j=next[j];
         
  }

        
if(j>(int)(t[0])) return i-((int)(t[0]));
        
else return 0;

  }

/***************++++INIT+++*****************************************/
    
void init(string ss,string tt)
 
{
       
//cout<<"请输入原串S=: "<<endl;
       
//cin>>s1;
       
//cout<<"请输入模式串T=:"<<endl;
       
//cin>>t1;
       s1=ss;
       t1
=tt;
       m
=s1.length(); 
       n
=t1.length();
       
//if((s=(char*)malloc((m+1)*sizeof(char)))<0){cout<<"failed\n";return;}
       s=new char[m+1];
       s[
0]=m;
       
//if((t=(char*) malloc((n+1)*sizeof(char)))<0) {cout<<"failed\n";return;}
       t=new char[n+1];
       t[
0]=n;
       
for(int i=1;i<=m;i++)
      s[i]
=s1.at(i-1);
       
for( i=1;i<=n;i++)
         t[i]
=t1.at(i-1);
        cout
<<"原串为: ";    show(s,m);
     cout
<<"模式串为: ";  show(t,n);
        get_next(t,next); 
 }

/*******************++++SHOW+++**************************************/
       
void show(char s[],int n )
    
{
         
for(int i=1;i<=n;i++)
         cout
<<s[i]<<"  ";
         cout
<<endl;
         cout
<<"长度为: "<<int(s[0])<<"\n";
    }




文章来源:http://127.0.0.1/blog/hyouhaku/archive/2004/12/31/151.html

posted on 2005-01-02 15:07  hyouhaku  阅读(422)  评论(0编辑  收藏  举报

导航