KMP的模板题 问模式串在文本串中出现了几次,我这里求的next是定字符串的最长前缀和最长后缀相同的长度,还有一种速度应该是比这个快的求法
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
#define ls st<<1
#define rs st<<1|1
#define fst first
#define snd second
#define MP make_pair
#define PB push_back
#define LL long long
#define PII pair<int,int>
#define VI vector<int>
#define CLR(a,b) memset(a, (b), sizeof(a))
#define ALL(x) x.begin(),x.end()
#define rep(i,s,e) for(int i=(s); i<=(e); i++)
#define tep(i,s,e) for(int i=(s); i>=(e); i--)
const int INF = 0x3f3f3f3f;
const int MAXN = 2e5+10;
const int mod = 1e9+7;
const double eps = 1e-8;
void fe() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt","w",stdout);
#endif
}
LL read()
{
LL x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
return x*f;
}
int next[MAXN];
int kmp(string t, string p) {
int res = 0;
int i = 0, j = next[0] = -1;
int len_p = p.size();
int len_t = t.size();
while(i < len_p) {
while(j!=-1 && p[i]!=p[j])
j = next[j];
next[++i] = ++j;
}
i = j = 0;
while(i < len_t) {
while(j!=-1 && t[i]!=p[j])
j = next[j];
i++, j++;
if(j >= len_p) {
res++;
j = next[j];
}
}
return res;
}
string a, b;
int main(int argc, char const *argv[])
{
ios::sync_with_stdio(false);
int T;
cin >> T;
while(T--) {
a.clear();
b.clear();
cin >> a >> b;
cout << kmp(b, a) <<endl;
}
return 0;
}