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

华电北风吹
日期: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;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值