给出模式串和文本串,求模式串在文本串中共匹配几次。
套板子上就完了。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
#define IO \
ios::sync_with_stdio(false); \
// cin.tie(0); \
// cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 1e7 + 100;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
const double pi = acos(-1);
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
string p, t;
int nextp[maxn];
void Get_nextp(int n)
{
for (int i = 1; i < n; i++)
{
int j = i;
while (j > 0)
{
j = nextp[j];
if (p[i] == p[j])
{
nextp[i + 1] = j + 1;
break;
}
}
}
}
int Kmp(int lenp, int lent)
{
int i, j;
int ans = 0;
for (i = 0, j = 0; i < lent; i++)
{
if (j < lenp && t[i] == p[j])
j++;
else
{
while (j > 0)
{
j = nextp[j];
if (t[i] == p[j])
{
j++;
break;
}
}
}
if (j == lenp)
ans++;
}
return ans;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
IO;
int T;
cin >> T;
while (T--)
{
cin >> p >> t;
memset(nextp, 0, sizeof nextp);
Get_nextp(p.size());
cout << Kmp(p.size(), t.size()) << "\n";
}
return 0;
}