您的位置:首页 > 其它

To_review_100_4---Horspool算法的整理

2015-06-25 08:43 302 查看

思路:

    从后往前进行匹配。

    遇到模式串与主串不匹配时,根据主串的最后一个字符R的情况,模式串向右进行移动:

    1. 当模式串中不存在R时,直接越过R,向右移动模式串长度

    2. 当模式串中存在R时,找出模式串中最右的R'=R,并向右移动模式串,使得模式串的R’对上主串的R

例子:

    STEP1——

       主串:s u b s t  r  i n g _ s e a r c h i n g

    模式串:s e a r c h

    STEP2——

       主串:s u b s  t   r  i   n  g _  s e a r c h i n g

    模式串:     s e  a  r  c  h   

    STEP3——

       主串:s u b s t  r  i  n g _  s e a r c h i n g

    模式串:                       s e  a  r c h

    STEP4——

       主串:s u b s t  r  i  n g _  s e a r c h i n g

    模式串:                              s e a r c h

     END

C++代码:

#include <iostream>

using namespace std;

void MakeShift(char* ptrn, int pLen, int* shiftArray, int arrayLen = 256){

 for (int i = 0; i < pLen; i++)

  *(shiftArray + i) = pLen;

 while (pLen >= 0)

  *(shiftArray + (unsigned char)*ptrn++) = --pLen;

}

bool HorspoolSearch(char *buf, int bLen, char *ptrn, int pLen, int* shiftArray, int arrayLen = 256){

 int endMark = pLen-1;

 if (bLen < pLen || bLen == 0 || pLen == 0)

  return false;

 while (endMark < bLen){

  int b_temp = endMark;

  int p_temp = pLen-1;

  while (*(buf + b_temp--) == *(ptrn + p_temp--)){

   if (p_temp == -1)

    return true;

  }

  endMark += shiftArray[*(buf + b_temp + 1)];

 }

 return false;

}

int main(){

 int shiftArray[256];

 char *buf = "aabd";

 int bLen = 4;

 char *ptrn = "ab";

 int pLen = 2;

 MakeShift(ptrn, pLen, shiftArray);

 cout << HorspoolSearch(buf, bLen, ptrn, pLen, shiftArray) << endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: