KMP算法
来源:互联网 发布:笔记本软件限制策略 编辑:程序博客网 时间:2024/06/05 02:02
1,KMP算法思想:
每次出现不匹配字符时,不需要回溯,而是利用已得到的部分匹配结果将模式向右滑动尽可能远的距离,继续比较。
例如:s表示偏移距离。
KMP算法主要就是要求出模式P的next数组。代码如下:
#include <iostream>#include <vector>#include <string>using namespace std;vector<int> compute_next(string A){int length = A.length();vector<int> next(length);next[0] = 0;int k = 0;for (int i = 1; i < length; ++i){while (k > 0 && A[k] != A[i]){k = next[k];}if (A[k] == A[i]){k = k+1;}next[i] = k;}return next;}void KMP(){string str;string T;//文本Tcin >> T;while (cin >> str)//模式{int s = 0;//记录偏移位置vector<int> locate;//记录匹配位置vector<int> next(compute_next(str));//计算它的next数组for (unsigned int i = 0, j = 0; i < T.length() && j < str.length();){if (T[i] == str[j]){++i;++j;}else{if (j != 0){s = s + (j - next[j-1]);j = next[j-1];}else{++i;s = s+1;}}if (j == str.length()){locate.push_back(s);s = s + (j - next[j-1]);j = next[j-1];}}if (!locate.empty()){vector<int>::iterator it = locate.begin();for (; it != locate.end() - 1; ++it){cout << *it << " ";}cout << *it << endl;}elsecout << "NO!" << endl;}}int main(){KMP();system("pause");return 1;}部分输入和输出为:
1 0
- KMP算法详解 【KMP】
- 【KMP】KMP算法模板
- KMP hihoCoder1015 KMP算法
- kmp算法
- KMP算法
- KMP算法
- KMP算法
- KMP算法
- KMP 算法
- kmp算法
- KMP算法
- kmp算法
- KMP算法
- KMP算法
- kmp算法
- kmp算法
- KMP算法
- KMP算法
- POJ - 1065 Wooden Sticks(DP 子序列问题)
- 定制ListView的几个步骤
- html5定位
- 【Boost】Boost使用几条简单笔记
- CentOS 7.2 Mitaka云平台计算节点部署脚本(VLAN+VXLAN私有网络)
- KMP算法
- 顺序栈&链栈
- CodeForce 711B
- 80行代码搞定菜单展开动画
- Vim 添加中文帮助文档
- Android URI
- 基于Fast Trackingvia Spatio-Temporal Context Learning目标跟踪所感
- 字符串的排列
- 在Drupal中使用Restful之二