教材上关于模式匹配中的求next数组的算法不易理解,本人自己编写了一个具有相同功能的子函数

#include<stdio.h>
#include<string.h>
#define  W    9
#define  L    30
int next[W-1];
void   nextarray(char  t2[W],int next2[W-1])
{
int i=0,j,k,m,n;
printf("the original string t:/n");
for(n=1;n<strlen(t2);n++)
 {
  printf("%c",t2[n]);
 }
next2[1]=0;
next2[2]=1;
for(m=3;m<=W-2;m++)
{
  if(m%2==0)
  {
  j=m/2;
  }
 if(m%2!=0)
  {
  j=(m+1)/2;
  }
  i=0;
while(j<m)
 {
 if(t2[i]==t2[j])
   {
   i++;
   j++;
   }
 else
   {
   i=1;
   j++;
   }
 }
 if(j==m && i>0)
  {
  next2[m]=i;
  }
  else
  {
  next2[m]=1;
  }
}
printf("/n");
printf("here are values for next array:/n");
for(i=1;i<W-1;i++)
 {
 printf("%-5d",next2[i]);
 }
 for(i=0;i<3;i++)
 {
printf("/n");
 }
}
void  createstrt(char strt[W-1])
{
int i;
strt[0]='[';
printf("please input a string for  t (length< %d:/n",W-1);
for(i=1;i<W-1;i++)
 {
 scanf("%c",&strt[i]);
 }
 strt[W-1]='/0';
 printf("/n");
}
void  createstrs(char strs[L-1])
{
int i;
strs[0]='!';
printf("please input a string for  s (length< %d):/n",L-1);
for(i=1;i<L-1;i++)
 {
  scanf("%c",&strs[i]);
 }
 strs[L-1]='/0';
 printf("here are the string you have input:/n");
 for(i=1;i<=L-1;i++)
 {
 printf("%c",strs[i]);
 }
 printf("/n");
}
void  pipei(char  t2[W],char  s2[L],int next[W-1])
{
int i=1,j=1;
while(i<L && j<W)
  {
  if(t2[j]==s2[i])
    {
    i++;
    j++;
    }
  else
    {
     j=next[j];
     if(j==0)
       {
       j++;
       i++;
       }
    }
  }
if(j==W-1)
   {
   printf("string t is locted in the [%d] of the string s/n",i);
   }
 else
   {
   printf("string t is not in the  string s!/n");
   }
}
int main()
{
char  t[W],s[L];
clrscr();
createstrt(t);
createstrs(s);
nextarray(t,next);
pipei(t,s,next);
return  0;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值