解题思路:
典型KMP,直接搞。
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <algorithm> #include <cmath> #include <vector> #include <queue> #include <stack> #define LL long long #define FOR(i,x,y) for(int i=x;i<=y;i++) using namespace std; const int maxn = 1000000 + 10; char s[maxn], t[maxn]; int next[maxn]; void get_next() { int m = strlen(s); next[0] = 0; next[1] = 0; for(int i=1;i<m;i++) { int j = next[i]; while(j && s[i] != s[j]) j = next[j]; next[i+1] = (s[i] == s[j]) ? j + 1: 0; } } int KMP() { int n = strlen(t), m = strlen(s); get_next(); int j = 0, cnt = 0; for(int i=0;i<n;i++) { while(j && s[j] != t[i]) j = next[j]; if(s[j] == t[i]) j++; if(j == m) cnt++; } return cnt; } int main() { int T; scanf("%d", &T); while(T--) { scanf("%s%s", &s, &t); int ans = KMP(); printf("%d\n", ans); } return 0; }
时间: 2024-11-03 05:43:55