思路:
从后往前进行匹配。
遇到模式串与主串不匹配时,根据主串的最后一个字符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;
}