KMP代码

KMP代码
一:C语言:
#include <stdio.h>
void getnext(char *s,int next[])
{/*得到next数据,其实本质是自身KMP匹配*/
       int i,j;
       i=0;j=-1;next[0]=-1;
       while(s[i]){
         if(j==-1||s[i]==s[j]){
           ++i;++j;next[i]=j;
         }
         else j=next[j];
       } 
}
int kmp(char *m,char *s,int next[])
{
      /*返回s在m中的第一个字母的标*/
      int i,j;
      i=0;j=0;
      while(m[i]){
        if(j==-1||m[i]==s[j]){
          ++i;++j;
          if(s[j]=='/0') return (i-j);
        }
        else j=next[j];        
      } 
      return -1;
}
int main()
{
      char m[100],s[100];
      int next[100];
      scanf("%s",s);
      getnext(s,next);
      scanf("%s",m);
      printf("%d",kmp(m,s,next));
      getch();
      return 0; 
}
二:C++;
const vector<int> * kmp_next(string &m) // count the longest prefex string ;
{
static vector<int> next(m.size());
next[0]=0; // the initialization of the next[0];
int temp; // the key iterator......
for(int i=1;i<next.size();i++)
{
temp=next[i-1];
while(m[i]!=m[temp]&&temp>0)
{ temp=next[temp-1];
}
if(m[i]==m[temp])
next[i]=temp+1;
else next[i]=0;

}
return &next;
}

bool kmp_search(string text,string m,int &pos)
{
const vector<int> * next=kmp_next(m);
int tp=0;
int mp=0; // text pointer and match string pointer;
for(tp=0;tp<text.size();tp++)
{
while(text[tp]!=m[mp]&&mp)
mp=(*next)[mp-1];
if(text[tp]==m[mp])
mp++;
if(mp==m.size())
{ pos=tp-mp+1;
return true;
}
}
if(tp==text.size())
return false;
}
 
 
 
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值