KMP算法的实现
来源:互联网 发布:广州星知电子有限公司 编辑:程序博客网 时间:2024/05/19 03:45
本文来自hihoCoder1015题,已AC。统计字符串中出现的模式串的次数。
对于有两个字符串:
源字符串:ababcabcababcabcab
….模式串:abcabc
next数组:-1 0 0 0 1 2
匹配过程如下:
|a|b|a|b|c|a|b|c|a|b|a|b|c|a|b|c|a|b|
|–|–|a|b|c|a|b|c|–|–|–|–|–|–|–|–|–|–|
|–|–|–|–|–|a|b|c|a|b|c|–|–|–|–|–|–|–|
|–|–|–|–|–|–|–|–|–|–|a|b|c|a|b|c|–|–|
参考文献:
KMP算法学习&总结
代码如下:
#include <iostream>#include <vector>#include <string>using namespace std;void getNext(const string &pattern, vector<int> &next){ next.resize(pattern.size()); next[0] = -1; int i = 0, j = -1; while(i != pattern.size() - 1) { if(j == -1 || pattern[i] == pattern[j]) { i++; j++; next[i] = j; } else { j = next[j]; } }}int kmp(const string &source, const string &pattern){ vector<int> next(pattern.size()); getNext(pattern, next); int i = 0, j = 0; int count = 0; while(i != source.length() && j != pattern.length()) { if(j == -1 || source[i] == pattern[j]) { i++; j++; } else { j = next[j]; } if(j == pattern.length()) {//匹配到一个模式串后做处理,减少匹配次数 count++; i--; j = next[j - 1]; } } return count;}int main(){ int N; cin >> N; string p, s; while(N--) { cin >> p; cin >> s; cout << kmp(s, p) << endl; } return 0;}
0 0
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- kmp算法的实现
- kmp算法的实现
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- KMP算法的实现
- java实现的KMP算法
- C++实现的KMP算法
- KMP算法的JAVA实现
- iOS 9适配技巧(更新版)
- Table Layout
- jquery 实现可编辑的表格
- netbeans,界面组合框的点击刷新应用和从数据库提取数据添加到列表应用
- socket C#发送int整数delphi接收
- KMP算法的实现
- Android Animation 动画解析
- Redis与Memcached比较
- Quartz2D绘图<三>绘制图形
- iOS开发之 转场动画CATransition
- <读书.敏捷开发>1.关于敏捷开发的一点读后感
- 诡异的Qt eventFilter
- 获取指定格式时间戳(JSON注入)
- 浅谈网络编程的入门