第四章(4).KMP算法

来源:互联网 发布:python是用来做什么的 编辑:程序博客网 时间:2024/06/04 12:55

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

#define MAXSIZE  50    
typedef unsigned char SString[ MAXSIZE + 1 ] ;  //SString[ 0 ] 存储长度
int next[ MAXSIZE + 1 ] ;

void StrAssign(SString T, char *ch)        
{   //生成一个其值等于ch的串T
 int i;
 if(strlen(ch) > MAXSIZE)
 {
  exit(0);
 }
 else
 {
  T[0] = strlen(ch);       //串的第一位存储串的长度(整型)
  for( i = 1; i <= T[0]; i++ )
  {
   T[i] = *(ch + i - 1);     //(字符型)
  }
 }
}

void get_nextval( SString T , int nextval[ ] )
{ //求模式串T的next函数修正值并存入数组nextval
 int i = 1 , j = 0 ;
 nextval[ 1 ] = 0 ;

 while( i < T[ 0 ] )
 {
  if( j == 0 || T[ i ] == T[ j ] )
  {
   ++ i ; ++ j ;
   if( T[ i ] != T[ j ] )
    nextval[ i ] = j ;
   else
    nextval[ i ] = nextval[ j ] ;
  }
  else
   j = nextval[ j ] ;
 }

}

int Index_KMP( SString S , SString T , int pos )
{ //利用模式串T的next函数求T在主串S中第pos个字符之后的位置的KMP算法(1<= pos <= StrLength(S))
 int i = pos , j = 1 ;
 while( i <= S[ 0 ] && j <= T[ 0 ] )
 {
  if( j == 0 || S[ i ] == T[ j ] )
  {
   ++ i ;
   ++ j ;     //继续比较后续字符
  }
  else
   j = next[ j ] ;   //模式串向右移动
 }
 if( j > T[ 0 ] )
  return i - T[ 0 ] ;   //匹配成功
 else
  return 0 ;

int main()
{
 char *s = "acabaabaabcacaabc" ;
 char *t = "abaabcac" ;
 SString T , S ;

 StrAssign( S , s ) ;
 StrAssign( T, t ) ;

 get_nextval( T , next ) ;
 if( Index_KMP( S , T , 0 ) )
  printf( "匹配成功\n" ) ;
 else
  printf( "匹配不成功\n" ) ;

 return 0 ;
}


0 0
原创粉丝点击