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
原创粉丝点击