题目链接
题意:给你两个字符串s,t。让你求在s中t出现了多少次。
解题思路:
先写前缀函数(前缀函数的写法点这里了解)
然后就是常规KMP模板了。统计答案时重置pos_t的位置。
错误原因:对重置pos_t的操作不是很熟练,导致出了bug。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
//#pragma GCC optimize(3,"Ofast","inline")
#define LL long long
#define MT(a,b) memset(a,b,sizeof(a))
const int mod=1000007;
const int maxn=1e6+5;
const int ONF=-0x3f3f3f3f;
const int INF=0x3f3f3f3f;
char s[maxn],t[maxn];
int pi[maxn];
void get_pi(char *str){
int len=strlen(str);
pi[0]=0;
for (int i=1;i<len;i++){
int j=pi[i-1];
while (j>0&&str[i]!=str[j]) j=pi[j-1];
if (str[i]==str[j]) j++;
pi[i]=j;
}
}
int kmp(){
int len_t=strlen(t),len_s=strlen(s);
int pos_t=0,pos_s=0,ans=0;
if (len_t==1&&len_s==1){
if (s[0]==t[0]) return 1;
else return 0;
}
get_pi(t);
for (;pos_s<len_s;pos_s++){
while (pos_t>0&&s[pos_s]!=t[pos_t]){
pos_t=pi[pos_t-1];
}
if (s[pos_s]==t[pos_t]){
pos_t++;
}
if (pos_t==len_t) {
ans++;
pos_t=pi[pos_t-1];
}
}
return ans;
}
int main (){
int T;
scanf("%d",&T);
while (T--){
scanf("%s%s",t,s);
printf("%d\n",kmp());
}
return 0;
}