To_review_100_3---Sunday算法的整理
2015-06-24 21:45
316 查看
PS:前两天在看KMP算法以及BM算法时被虐哭了= =,今天看Sunday算法感觉好爽^_^,后面再整理几个模式匹配的算法,最后比较一下这几个模式匹配算法的性能
思路:
遇到模式串与主串不匹配时,根据主串中参加匹配的最末字符的下一位字符R的情况,模式串向右进行移动:
1. 当模式串中不存在R时,直接越过R,向右移动模式串长度+1
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
END
C++代码:
void MakeShift(char* ptrn, int pLen, int* shiftArray, int arrayLen = 256){
for (int i = 0; i < arrayLen; i++)
*(shiftArray + i) = pLen + 1;
while (pLen != 0)
*(shiftArray + (unsigned char)*ptrn++) = pLen--;
}
bool SundaySearch(char *buf, int bLen, char *ptrn, int pLen, int* shiftArray, int arrayLen=256){
int b_idx = pLen;
if (bLen < pLen || bLen == 0 || pLen == 0)
return false;
while (b_idx <= bLen){
int p_idx = 0;
int temp_idx=b_idx-pLen;
while (*(buf + temp_idx++) == *(ptrn + p_idx++)){
if (p_idx == pLen)
return true;
}
b_idx += shiftArray[*(buf+b_idx)];
}
return false;
}
int main(){
int shiftArray[256];
char *buf = "aabd";
int bLen = 4;
char *ptrn = "abd";
int pLen = 3;
MakeShift(ptrn, pLen, shiftArray);
cout << SundaySearch(buf, bLen, ptrn, pLen, shiftArray) << endl;
}
思路:
遇到模式串与主串不匹配时,根据主串中参加匹配的最末字符的下一位字符R的情况,模式串向右进行移动:
1. 当模式串中不存在R时,直接越过R,向右移动模式串长度+1
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
END
C++代码:
void MakeShift(char* ptrn, int pLen, int* shiftArray, int arrayLen = 256){
for (int i = 0; i < arrayLen; i++)
*(shiftArray + i) = pLen + 1;
while (pLen != 0)
*(shiftArray + (unsigned char)*ptrn++) = pLen--;
}
bool SundaySearch(char *buf, int bLen, char *ptrn, int pLen, int* shiftArray, int arrayLen=256){
int b_idx = pLen;
if (bLen < pLen || bLen == 0 || pLen == 0)
return false;
while (b_idx <= bLen){
int p_idx = 0;
int temp_idx=b_idx-pLen;
while (*(buf + temp_idx++) == *(ptrn + p_idx++)){
if (p_idx == pLen)
return true;
}
b_idx += shiftArray[*(buf+b_idx)];
}
return false;
}
int main(){
int shiftArray[256];
char *buf = "aabd";
int bLen = 4;
char *ptrn = "abd";
int pLen = 3;
MakeShift(ptrn, pLen, shiftArray);
cout << SundaySearch(buf, bLen, ptrn, pLen, shiftArray) << endl;
}
相关文章推荐
- Recognizer API
- 程序实现自己删除
- Android 自定义View measure模板
- Leetcode 219 Contains Duplicate II
- 软件工程问题及回答
- 关于preg_match和preg_match_all
- 支持向量机SVM(二)
- 关于Ui组件之WebView详解
- LeetCode Divide Two Integers
- 60.根据公式计算值
- 新手Oracle安装及使用入门
- 场景的总结以及音效(四)
- 继承
- 2015-6-24add loading sprite and repeat rotate;
- 1036. Boys vs Girls (25)
- dspace搭建过程
- 继承和组合
- 思科rip、dhcp、vlan
- malloc()函数和calloc()函数的区别
- 支持向量机SVM(一)