poj 3461

来源:互联网 发布:三菱变频器软件 编辑:程序博客网 时间:2024/05/17 23:16

#include <iostream>#include <string>#include <vector>#include <iterator>int acc = 0;void calc_next(const std::string &p, std::vector<int> &next){next.assign(p.length(), -1);std::string::size_type i = 0;int j = -1;next[0] = -1;while(i < p.length() - 1){if((-1 == j) || (p[i] == p[j])){++i;++j;if(p[i] == p[j]){next[i] = next[j];}else{next[i] = j;}}else{j = next[j];}}}std::string::size_type kmp(const std::string &s, const std::string &p, const std::string::size_type pos, const std::vector<int> &next){std::string::size_type i = pos;int j = 0;while ((i < s.length()) && ((-1 == j) || (j < p.length()))){if((-1 == j) || (s[i] == p[j])){if (p[j + 1] == '#'){++acc;}++i;++j;}else{j = next[j];}}if (p.length() == j){return i - p.length();}else{return std::string::npos;}}std::string::size_type kmp_match(const std::string &s, const std::string &p, const std::string::size_type pos = 0){if(s.empty() || p.empty() || (p.length() > s.length())){return std::string::npos;}if(pos > s.length() - p.length()){return std::string::npos;}std::vector<int> next;calc_next(p, next);return kmp(s, p, pos, next);}int main(){int num = 0;std::cin >> num;for (; num > 0; --num){std::string str;std::string pat;std::cin >> pat >> str;str.push_back('#');pat.push_back('#');acc = 0;kmp_match(str, pat);std::cout << acc << std::endl;}return 0;}

0 0
原创粉丝点击