题目链接:https://cn.vjudge.net/contest/388654#status/2019030001040/B/0/
字符串匹配 KMP模板题
#include <iostream> #include <algorithm> #include <cstdlib> #include <cstring> #include <string> #include <cmath> #include <vector> #include <queue> using namespace std; typedef long long ll; char str[1000005], pattern[10005]; int Next[10005]; int cnt; void getFail(char* p, int plen) { Next[0] = 0, Next[1] = 0; for (int i = 1; i < plen; i++) { int j = Next[i]; while (j && p[i] != p[j]) j = Next[j]; Next[i + 1] = (p[i] == p[j]) ? j + 1 : 0; } } void kmp(char* s, char* p) { int last = -1; int slen = strlen(s), plen = strlen(p); getFail(p, plen); int j = 0; for (int i = 0; i < slen; i++) { while (j && s[i] != p[j]) j = Next[j]; if (s[i] == p[j]) j++; if (j == plen) { cnt++; last = i; } } } int main() { int t; scanf("%d", &t); while (t--) { scanf("%s", pattern); scanf("%s", str); cnt = 0; kmp(str, pattern); printf("%d ", cnt); } return 0; }