KMP-返回匹配次數
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
#define LL long long
#define maxn 10010
#define mod 100000007
char a[maxn * 100], b[maxn];
int Next[maxn], n, m;
void Get_Next(char b[], int m)
{
int i, j;
j = Next[0] = -1;
i = 0;
while (i < m)
{
while (j != -1 && b[i] != b[j])
j = Next[j];
Next[++i] = ++j;
}
}
int kmp(char a[], char b[])
{
int ans, i, j;
i = j = ans = 0;
Get_Next(b, m);
while (i < n)
{
while (j != -1 && a[i] != b[j])
j = Next[j];
j++, i++;
if (j == m)
{
ans++;
j = Next[j];///匹配成功後,當做失配,移動j到Next處
}
}
return ans;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
scanf("%s %s", b, a);
n = strlen(a);
m = strlen(b);
printf("%d\n", kmp(a, b));
}
return 0;
}