字符串匹配_2

来源:互联网 发布:电脑软件开发学校 编辑:程序博客网 时间:2024/06/06 00:26
/*
问题描述:字符串匹配,KMP算法
来源:网易算法课
日期:2017-11-6

*/

#include <iostream>#include <string>#include <vector>using namespace std;class KMP{public:KMP(string P){int length = P.length() + 1;this->P = P;for (int i = 0; i < length; i++)next.push_back(-1);next[1] = 0;}//生成next数组void generateNext(){for (int i = P.length(); i > 0; i--){next[i] = getLongestSuffix(i);}}//匹配操作int match(string T){int n = T.length();int m = P.length();int q = 0;for (int i = 0; i < n; i++){while (q > 0 && P[q] != T[i]){q = next[q];}if (P[q] == T[i]){q = q + 1;}if (q == m)return i - m + 1;}}private:string P;vector<int> next;//获取最长后缀int getLongestSuffix(int s){if (next[s] != -1)return next[s];next[s] = 0;int k = getLongestSuffix(s - 1);do{if (P[k] == P[s - 1]){next[s] = k + 1;return next[s];}if (k > 0){k = getLongestSuffix(k);}} while (k > 0);return next[s];}};void main(){string T = "abababacaba";string P = "ababaca";KMP kmp(P);kmp.generateNext();cout << kmp.match(T);}