[数据结构]KMP算法实现

#include < stdio.h >
#include
< stdlib.h >
#define  MAX 255

void  get_next( const   char *  T, int *  next)  //  算法4.7
{
    
int  i = 0 ,j =- 1 ;
    next[
0 ] =- 1 ;
    
while  (i < strlen(T)) {
        
if (j ==- 1   ||  T[i] ==  T[j]) {
            
++ i;   ++ j;  next[i]  =  j;
        }
        
else     j =  next[j];
    }
}

int  Index_KMP( const   char *  S,  const   char *  T) {   //  算法4.6
    int *  next = ( int * )malloc( sizeof ( int ) * strlen(T));
   
int  i = 0 , j = 0 ;
   get_next(T, next);
   
while  (i  <  strlen(S)  &&  j  <  strlen(T)) 
   {
      
if  (j  ==   - 1   ||  S[i]  ==  T[j]) {
      
++ i;   ++ j;
      } 
      
else  j  =  next[j];
   }
  
if  (j  >=  strlen(T))  return   i - strlen(T);
  
else   return   0 ;


/*
int Index (char S[], char T[])  //模式匹配算法
{
int i=0;
int j=0;
while (S[i]!='/0'&&T[j]!='/0')
{
    if (S[i]==T[j]) {++i;++j;}
    else {i = i-j+1;j=0;}
}
if ( T[j]=='/0') return i-strlen(T);
else return 0;
}
*/

void  main()    // 主函数
{
  
char  str1[MAX];
  
char  str2[MAX];
  
int  position = 0 ;
  
int  i,j;
  
int  l;
  printf(
" 请输第一个字符串: " );
  gets(str1);
  printf(
" 请输第二个字符串: " );
  gets(str2);
  l
= strlen(str2);
  position
= Index_KMP(str1, str2);
  
// position=Index(str1,str2) ;
   if  (position == 0 )
      printf(
" 没有匹配! " );
  
else
  {
      
for (i = 0 ;i < position;i ++ ) {str2[i] = str1[i];}
      j
= i + l;
      
while (str1[j] != '/ 0 '
      {str2[i]
= str1[j]; i ++ ; j ++ ;}
      str2[i]
= ' /0 ' ;
      printf(
" 结果为:%s " ,str2);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值