To_review_100_4---Horspool算法的整理



思路:

    从后往前进行匹配。

    遇到模式串与主串不匹配时,根据主串的最后一个字符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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值