梁田的专栏

充实每一天

原创 今天学会了用于模式匹配的KMP算法,思路太精彩了!! 收藏

新一篇: 学数据结构的意义 | 旧一篇: 这篇文章让我感触很深,是一位HR写的

以下是两种模式匹配的算法,前者为普通算法,后者为KMP算法
Index(char S[],char Sub[])
{
 int i=0,j=1;
 while (i<=S[0]&&j<=Sub[0])
 {
  if(S[i]==Sub[j])
  {
   i++;
   j++;
  }
  else
  {
   i=i-j+2;
   j=1;
  }
 }
 if (j>Sub[0])
 return i-Sub[0];
 else
 return 0;
}

Index_KMP(char S[],char Sub[])
{
 int next[MAXSIZE],i=0,j=1;
 Get_next(Sub,next);
 while (i<=S[0]&&j<=Sub[0])
 {
  if (j==0||S[i]==Sub[j])
  {
   i++;
   j++;
  }
  else
  j=next[j];
 }
 if (j>Sub[0])
 return i-Sub[0];
 else
 return 0;
}
Get_next(char Sub[],int next[])
{
 int i=1,j=0;
 next[1]=0;
 while(i<=Sub[0])
 {
  if (j==0||Sub[i]==Sub[j])
  {
   i++;
   j++;
   if (Sub[i]!=Sub[j])
   next[i]=j;
   else
   next[i]=next[j];
  }
  else
  j=next[j];
 }
}

发表于 @ 2006年11月26日 17:31:00|评论(loading...)|编辑

新一篇: 学数据结构的意义 | 旧一篇: 这篇文章让我感触很深,是一位HR写的

评论:没有评论。

发表评论  


登录
Csdn Blog version 3.1a
Copyright © czlt