版权声明: https://blog.csdn.net/moon_sky1999/article/details/83703143
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1686
kmp模板题。
代码:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define ll long long
#define ull unsigned long long
#define BUG cout<<"*************************"<<endl
using namespace std;
const ll mod = 1e9;
const int maxn = 5e4 + 10;
const int maxm = 1e6 + 10000;
const double eps = 1e-8;
int nxt[maxm];
string s, t;
void get_next(int len) {
int j = 0, k = -1;
nxt[0] = -1;
while (j < len) {
if (k == -1 || t[k] == t[j]) {
++j;
++k;
nxt[j] = k;
} else k = nxt[k];
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int _;
cin >> _;
while (_--) {
cin >> t >> s;
get_next((int) t.size());
int i = 0, j = 0, ans = 0;
while (i < s.size()) {
if (j == -1 || s[i] == t[j]) {
++i;
++j;
} else j = nxt[j];
if (j == t.size()) {
++ans;
j = nxt[j];
}
}
cout << ans << endl;
}
return 0;
}