KMP算法

// KMP算法

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 
void get_next(char *T,int next[])	//修正前的next数组 
  {
    int i = 1,j = 0;
    next[0] = -1;
    next[1] = 0;
    int m = strlen(T);
  while(i<strlen(T)-1)
  {
    if(j == -1||T[j]==T[i])
  {
    ++i;
    ++j;
   next[i] = j;
 }
    else j = next[j];
 }
 } 
 








void get_nextval(char *T,int nextval[])	//修正后的nextval数组
{
   int i = 1,j = 0;
   nextval[0] = -1;
   nextval[1] = 0;
   int m = strlen(T);
   while(i<strlen(T)-1)
  {
   if(j == -1||T[j]==T[i])
   {
     ++i;
     ++j;
     if(T[i]!=T[j]) 
     nextval[i] = j;
    else nextval[i] = nextval[j];
    }
   else j = nextval[j];
}
} 
 
int Index_kmp(char *S,char *T,int pos,int next[])	//逐项比较 
{
   int j = 0,i = pos,len1=strlen(S),len2=strlen(T);
   get_next(T,next);
   while(i<len1&&j<len2)
   {
    if(S[i]==T[j]||j==-1)
   {
    i++;j++;
   }
    else j = next[j];
   }
    if(j>=len2) return i-len2;
   else return -1;
}
 
int main()
{
   char *S="aab",*T="ab";
   int m;
   int *next = (int *)malloc((strlen(T)+1)*sizeof(int));	//修正前的next数组
   int *nextval = (int *)malloc((strlen(T)+1)*sizeof(int));	//修正后的nextval数组
 
   get_next(T,next);
   printf("nextarray:");
   for(m = 0;m<strlen(T);m++)
   {
    printf("%d ",next[m]+1);
   }
 
   get_nextval(T,nextval);
   printf("\n nextvalue:");
   for(m=0;m<strlen(T);m++)
   {
   printf("%d ",nextval[m]+1);
   }
 
 
   int t = Index_kmp(S,T,0,nextval);
   if(t==-1) printf("\n not match!\n");
   else
   {
    printf("\n at the %d match\n",t+1);
   }
   return 0;
}

运行代码如下

void get_next(char *T,int next[])	//修正前的next数组 
  {
    int i = 1,j = 0;//i是后缀,j是前缀,i比j大
    next[0] = -1;
    next[1] = 0;
    int m = strlen(T);
  while(i<strlen(T)-1)
  {
    if(j == 0||T[i]==T[j])//i的值为3,j的是1  j=0,从第一个进去  
    {
     ++i;//i的值为4
     ++j;//j的值为2
     next[i] = j;//next[i]的值为2
   }
     else j = next[j];//回溯 在4这里失配,找4的next的值,next[4]=2,把2对应的下标又是4,j等于4
 }
 } 
 

next数组详解
字串T

从相等的时候推下来
j=0开始推

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值