hihoCoder #1015之KMP算法

来源:互联网 发布:游戏视频后期制作软件 编辑:程序博客网 时间:2024/06/18 10:19
#include <iostream>#include <string>#include <vector>using namespace std;class Solution {public:int kmp_search(const string &s, const string &p){if(s.size() < p.size()) return 0;vector<int> next(p.size()+1, 0);get_next(p, next);int i(0), j(0), res(0);while(i < s.size()){if(j == -1 || (j < p.size() && s[i] == p[j])){++i;++j;}else j = next[j];if(j == p.size()) ++res;}return res;}void get_next(const string &p, vector<int> &next){int i(0), j(-1);next[i] = j;while(i < p.size()){if(j == -1 || p[i] == p[j]){++i;++j;//next[i] = j;if(p[i] != p[j]) next[i] = j;else next[i] = next[j];}else j = next[j];}}};int main(){int num;cin >> num;vector<int> res;while(--num >= 0){string s, p;cin >> p >> s;Solution solution;res.push_back(solution.kmp_search(s, p));}for(int i = 0; i < res.size(); ++i){cout << res[i];if(i < res.size() -1) cout << endl;}//system("PAUSE");return 0;}

0 0