LibreOJ #103.子串查找 KMP
题目描述
输入格式
输出格式
样例
数据范围与提示
题目分析
裸题kmp
AC代码
#include<iostream> #include<string> using namespace std; const int maxn = 1000010; string s, p; int _next[maxn]; void getnext(string p){ _next[0] = -1; int j = 0, k = -1; while (j < p.length() - 1){ if (k == -1 || p[j] == p[k]){ j++; k++; _next[j] = k; } else k = _next[k]; } } int kmp(string s, string p){ getnext(p); int i = 0,j = 0; int res = 0; while (i < s.length()){ if (j == -1 || s[i] == p[j]){ i++; j++; } else j = _next[j]; if (j == p.length()) { res++; i--; j--; j = _next[j]; } } return res; } int main() { ios::sync_with_stdio(false); cin >> s >> p; cout << kmp(s, p) << endl; return 0; }
题解效率


浙公网安备 33010602011771号