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;
}
思路:
从后往前进行匹配。
遇到模式串与主串不匹配时,根据主串的最后一个字符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;
}
相关文章推荐
- 真机测试的步骤
- 【转载】C++中的static关键字的总结
- android系统通知栏提示消息
- 撕逼不分对错 互联网电视迎来百家争鸣元年
- HAProxy高并发问题解决
- 内存的分配与回收
- Python标准库3.4.3-webbrowser-21.1
- SQL存储过程使用参考代码
- sierrawireless
- 实验四
- Win10最新手机预览版Build 10145要来了
- Apache Felix环境配备
- 小米与乐视的战争,全面剖析口水战背后的商业逻辑
- Linux在中国的没落
- iOS 阶段学习第七天笔记(函数、递归)
- Win10价格是多少?Windows 10欧美地区零售价官方公布
- Oracle dblink初始(一)
- 乐视2千字长文开喷小米:战胜也只能停留在发布会上
- iOS: 如何正确的绘制1像素的线
- 配置Maven