kmp算法的实现,严蔚敏版本(调试成功)

 学数据结构时看书算法编的
kmp算法的实现,严蔚敏版本(调试成功)

code:

/************/


main.cpp

#include "stdio.h"
#include "setting.h"

void main()
{
 int pos,result,count;
 SString S,T;
 char *p,*q;

 p = S;
 q = T;
 count=1;

 printf( "请输入主串S:" );
 scanf("%s",p);

 printf( "请输入模串T:" );
 scanf("%s",q);

 printf( "请输入S中第一个进行匹配的字符的位置pos:" );
 scanf( "%d",&pos );

 result = Index_KMP( S,T,pos,count );
 
 if( result == 0 )
  printf( "匹配不成功!/n" );
 else
  printf( "匹配成功,相匹配的位置是:%d/n",result );

 printf( "总共经过%d次匹配/n",count );
}

 /********************/

kmp_operation.cpp

#include "setting.h"

int Index_KMP( SString S,SString T,int pos ,int &count)
{
 int i,j,Len_s,Len_t;
 int next[256];

 i = pos;
 j = 1;

 Len_s = StrLength( S );
 Len_t = StrLength( T );

 get_next( T,next );

 while( i <= Len_s && j <= Len_t )
 {
  if( j == 0 || S[i - 1] == T[j - 1] )
  {
   i++;
   j++;
  }
  else
  {
   j = next[j];
   count++;
  }
 }

 if( j > Len_t)
  return i - Len_t;
 else
  return 0;
}

void get_next( SString T,Next next )
{
 int i,j,Len_t;

 i = 1;
 j = 0;
 next[1] = 0;

 Len_t = StrLength( T );

 while( i < Len_t )
 {
  if( j == 0 || T[i - 1] == T[j - 1] )
  {
   i++;
   j++;
   next[i] = j;
  }
  else
   j = next[j];
 }
}

status StrLength( SString S )
{
 int i;
 i = 0;

 while( *(S + i) != '/0' )
 {
  i++;
 }

 return i;
}

/*************************/

 setting.h

#define  MAXSTRLEN   255

typedef int status;
typedef char SString[MAXSTRLEN + 1];
typedef int Next[MAXSTRLEN + 1];


int Index_KMP( SString ,SString ,int ,int & );

void get_next( SString ,Next  );

status StrLength( SString S );

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值