您的位置:首页 > 其它

算法导论—Boyer-Moore(BM)算法

2016-02-26 17:35 211 查看
华电北风吹

日期:2016/2/25

BM算法精要:

BM算法比KMP更高效。KMP是基于对匹配字符串挨个比较,而且对于某些前缀字符串对应的字符可能比较的次数要不止一次。BM的思路是构造坏字符规则和好后缀规则,每一次尽量多的过滤掉不用匹配的那些字符。

参考资料:

字符串匹配的Boyer-Moore算法

BM算法详细图解

参考代码:

本文写的这个BM实现比较高效,模式预处理O(m),模式匹配最好情况O(n/m),比较理想。

#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;

class Solution
{
public:
vector<int> GoodPostFix(string pattern)
{
int m = pattern.size();
vector<int> post(m), goodfix(m + 1);
int i, j;
for (i = m - 2; i >= 0; i--)
{
j = post[i + 1];
while (j && pattern[i] != pattern[m - j - 1])
j = post[m - j];
post[i] = pattern[i] == pattern[m - j - 1] ? j + 1 : 0;
}
i = 1, j = m - 1;
while (j >= 0)
{
if (post[j] == i)
{
goodfix[m - i] = m - j - i;
i++;
}
j--;
}
while (i < m)
{
goodfix[m - i] = m - post[0];
i++;
}
return goodfix;
}

vector<int> BM(string str, string pattern)
{
vector<int> result;
int n = str.size(), m = pattern.size();
map<char, int> badmap;
for (int i = 0; i < m; i++)
badmap[pattern[i]] = i + 1;
vector<int> goodfix = GoodPostFix(pattern);
int k = 0;
while (k < n - m + 1)
{
int i = m - 1;
while (i >= 0)
{
if (str[k + i] != pattern[i])
{
int step = i - badmap[str[k + i]] + 1;
step = (step > goodfix[i + 1] ? step : goodfix[i + 1]);
k += step;
break;
}
i--;
}
if (i == -1)
{
result.push_back(k);
k++;
}
}
return result;
}
};

int main()
{
Solution s;
string str = "HERE IS A SIMPLE EXAMPLE";
string pattern = "EXAMPLE";
vector<int> v = s.BM(str, pattern);
for (auto i : v)
cout << i << endl;

getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: