算法导论—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),比较理想。
日期: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; }
相关文章推荐
- 黑客帝国效果
- 创建环境使用的存储过程
- Spark MLlib 1.6 -- 聚类
- jQuery基础知识之选择器
- 关于aspx 页面生成html 源码顶部空行不得不说的事儿
- ios runtime(1)
- 在Nodejs中贯彻单元测试
- oracle数据库imp导入报错IMP-00002
- 在MyEclipse中安装SVN插件subclipse
- hive使用小结
- Spring中@Autowired注解、@Resource注解的区别
- 在Eclipse中管理Java类引用的技巧
- poj 1151 Atlantis && codeforces #337 D. Vika and Segments (线段树+扫描线)(求面积并)
- 二叉搜索树
- OkHttp3源码分析
- [BZOJ1076] [SCOI2008]奖励关
- Ripsaw EV2 Extreme Luxury Super Tank 2015
- cocoaPods配置
- 年终总结
- git遇到的问题