串的模式匹配

来源:互联网 发布:淘宝怎么预约快递寄件 编辑:程序博客网 时间:2024/05/16 09:48

在串的各种操作中,串的模式匹配是经常用到的一个算法。串的模式匹配也称为子串的定位操作,即查找子串在主串中出现的位置。

1.经典的模式匹配算法Brute-Force。

2.KMP算法。

#include <stdio.h>  #include <stdlib.h>  #include <string.h>    #define MAXSIZE 60    typedef struct  {      char ch[MAXSIZE];      int length;  }SeqString;#include "SeqString.h"  /*经典的模式匹配算法Brute-Force*/  /*假设串采用顺序存储方式存储,则Brute-Force匹配算法如下*/    int B_FIndex(SeqString S,int pos,SeqString T)  /*在主串S中的第pos个位置开始查找子串T,如果找到,返回子串在主串中的位置;否则返回-1*/  {      int i,j;      i = pos-1;      j = 0;      while(i < S.length && j < T.length)      {          if(S.ch[i] == T.ch[j])              /*如果串S和串T中对应的位置的字符相等,则继续比较下一个字符*/          {              i++;              j++;          }          else              /*如果当前对应位置的字符不相等,则从串S的下一个字符开始,从T的第0个字符开始比较*/          {              i = i-j+1;              j = 0;          }      }      if(j >= T.length)          /*如果在串S中找到串T,则返回子串T在主串S中的位置*/      {          return i-j+1;      }      else      {          return -1;      }  }  #include "SeqString.h"  /*KMP算法*/  /*KMP算法思想*/  /*利用模式串T的next函数值求T在主串S中的第pos个字符之间的位置的KMP算法描述如下:*/    int KMP_Index(SeqString S,int pos,SeqString T,int next[])  {      int i,j;      i = pos-1;      j = 0;      while(i < S.length && j < T.length)      {          if(-1 == j || S.ch[i] == T.ch[j])              /*如果j=-1或当前字符相等,则继续比较后面的字符*/          {              i++;              j++;          }          else/*如果当前字符不相等,则将模式串向右移动*/          {              j = next[j];/*数组next保存next函数值*/          }      }      if(j >= T.length)/*匹配成功,则返回子串T在主串S中的位置,否则返回-1*/      {          return i-T.length+1;      }      else      {          return -1;      }  }  #include "SeqString.h"  /*KMP算法*/  /*求next函数值*/  /*算法描述如下*/  void GetNext(SeqString T,int next[])  {      int j,k;      j = 0;      k = -1;      next[0] = -1;      while(j < T.length)      {          if(-1 == k || T.ch[j] == T.ch[k])          {              j++;              k++;              next[j] = k;          }          else          {              k = next[k];          }      }  }  #include "SeqString.h"  /*KMP算法*/  /*求next函数值*/  /*改进算法如下*/  void GetNextVal(SeqString T,int nextval[])  {      int j,k;      j = 0;      k = -1;      nextval[0] = -1;      while(j < T.length)      {          if(-1 == k || T.ch[j] == T.ch[k])          {              j++;              k++;              if(T.ch[j] != T.ch[k])              {                  nextval[j] = k;              }              else              {                  nextval[j] = nextval[k];              }          }          else          {              k = nextval[k];          }      }  }  


0 0