Boyer-Moore算法是经典的字符串匹配算法。 当然要掌握它啦。 算法的具体解释参考阮一峰的博客。 解释相当之透彻。
链接为:http://www.ruanyifeng.com/blog/2013/05/boyer-moore_string_search_algorithm.html
我个人的理解为: 如果匹配模型(pattern)和字符串中的子串(sub_str)如果不相等的话。 那么从pattern的倒数第二个字符开始查找sub_str中的最后一个字符(ch)在pattern中的位置。 如果存在, 则记下其position(pos)。如果不存在 ,则为-1.
那么计算pattern在字符串中移动的位数为: step = strlen(pattern) - pos;
具体代码如下:
#include <iostream>
#include <Windows.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int BM(char *source, char *pattern)
{
int s_len = strlen(source);
int p_len = strlen(pattern);
int step = p_len;
int i = p_len - 1;
while (i < s_len)
{
char *s = new char[p_len+1];
memset(s, 0x00, p_len + 1);
strncpy(s, source+i-p_len+1, p_len);
int k = i;
int j = p_len - 1;
if (strcmp(s, pattern)== 0)
{
delete [] s;
return i - p_len + 1;
} else
{
while (j >= 0)
{
if (source[k] == pattern[j] && j != p_len - 1)
{
step = p_len - 1 - j;
delete [] s;
break;
} else
{
--j;
}
if (j == -1)
{
delete [] s;
}
} //while
} //else
i += step;
} //while
return -1;
}
int main(int argc, char **argv)
{
// test code.
char *s = "hello, world";
char *p = "world";
int rt = BM(s, p);
cout << rt << endl;
Sleep(15000);
return 0;
}
如果错误欢迎指正, 欢迎各种拍砖和讨论。
本文详细介绍了Boyer-Moore算法的工作原理,并通过一个具体的C++实现示例展示了如何利用该算法进行高效的字符串匹配。算法的核心在于利用模式串的特征来减少不必要的比较。
872

被折叠的 条评论
为什么被折叠?



