数据结构-无回溯串匹配

没啥好说的,理解代码是王道

  1  //  NoRemountStringMatch.cpp : 定义控制台应用程序的入口点。
  2  //
  3 
  4  #include  " stdafx.h "
  5  #include  < stdio.h >
  6  #include  < stdlib.h >
  7 
  8  #define  MAXNUM 100
  9  struct  SeqString
 10  {
 11       char  c[MAXNUM];
 12       int  n;
 13  };
 14  typedef  struct  SeqString  *  PSeqString;
 15 
 16 
 17  PSeqString createNullStr_seq( void )
 18  {
 19      PSeqString pstr;
 20      pstr  =  (PSeqString)malloc( sizeof ( struct  SeqString));
 21       if (pstr  ==  NULL)
 22          printf( " Out of space!!\n " );
 23       else
 24          pstr -> =   0 ;
 25       return (pstr);
 26  }
 27 
 28  // p0pi-1 中最大相同的前缀与后缀的长度k
 29  // next[i] = k;
 30  void  makeNext(PSeqString p,  int   *  next)
 31  {
 32       int  i,k;
 33      k  =   - 1 ;
 34      i  =   0 ;
 35      next[ 0 =   - 1 ;
 36       while (i  <  p -> -   1 )
 37      {
 38           // 找出p0pi中最大的相同的前缀长度k
 39           // 此段代码技巧性太强,要深入了解,要是我自己写肯定写不出来
 40           while (k  >=   0   &&  p -> c[i]  !=  p -> c[k])
 41              k  =  next[k];
 42          i ++ ;
 43          k ++ ;
 44           if (p -> c[i]  ==  p -> c[k])
 45              next[i]  =  next[k];
 46           else
 47              next[i]  =  k;
 48      }
 49  }
 50 
 51  // 无回溯的模式匹配算法
 52  int  pMatch(PSeqString t, PSeqString p,  int   *  next)
 53  {
 54       int  i,j;
 55      i  =   0 , j  =   0 ;
 56       while (i  <  p -> &&  j  <  t -> n)
 57           if (i  ==   - 1   ||  p -> c[i]  ==  t -> c[j])
 58          {
 59              i ++ ;
 60              j ++ ;
 61          }
 62           else
 63              i  =  next[i];
 64       if (i  >=  p -> n)
 65           return (j  -  p -> +   1 );
 66       else
 67           return ( 0 );
 68 
 69  }
 70 
 71  int  _tmain( int  argc, _TCHAR *  argv[])
 72  {
 73      PSeqString t  =  createNullStr_seq();
 74      PSeqString q  =  createNullStr_seq();
 75       int  location  =   0 ;
 76       int  next[ 3 ];
 77      t -> =   10 ;
 78      q -> =   3 ;
 79       // "ababbaabaa"
 80       // "aab"
 81      t -> c[ 0 =   ' a ' ;
 82      t -> c[ 1 =   ' b ' ;
 83      t -> c[ 2 =   ' a ' ;
 84      t -> c[ 3 =   ' b ' ;
 85      t -> c[ 4 =   ' b ' ;
 86      t -> c[ 5 =   ' a ' ;
 87      t -> c[ 6 =   ' a ' ;
 88      t -> c[ 7 =   ' b ' ;
 89      t -> c[ 8 =   ' a ' ;
 90      t -> c[ 9 =   ' a ' ;
 91      q -> c[ 0 =   ' a ' ;
 92      q -> c[ 1 =   ' a ' ;
 93      q -> c[ 2 =   ' b ' ;
 94      makeNext(q, next);
 95      location  =  pMatch(t, q, next);
 96      printf( " Location is: %d " , location);
 97       return   0 ;
 98  }

 运行结果:

Location is: 6


转载于:https://www.cnblogs.com/LarmanYuan/archive/2009/05/22/1487245.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值