字符串匹配算法
时间复杂度O(n+m)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
#define sf scanf
#define pf printf
#define fi first
#define se second
#define pb push_back
#define pll pair<ll,ll>
const int mod=1e9+7;
const int N=1e5+9,M=5e4+9;
char s[N],a[N];
int b[N];
int n,m;
void kmp()
{
int ans=0;
for(int i=1;i<=max(n,m);i++)
b[i]=0;
for(int x=0,i=2;i<=m;i++)
{
while(x>0&&a[x+1]!=a[i])
x=b[x];
if(a[x+1]==a[i])
x++;
b[i]=x;
}
for(int x=0,i=1;i<=n;i++)
{
while(x>0&&a[x+1]!=s[i])
x=b[x];
if(a[x+1]==s[i])
x++;
if(x==m)
{
x=b[x];
ans++;
}
}
pf("%d\n",ans);
}
void f0(int T)
{
sf("%s",a+1);//a子串,s主串
sf("%s",s+1);
m=strlen(a+1);
n=strlen(s+1);
kmp();
}
int main()
{
int T=1;
// sf("%d",&T);
for(int i=1;i<=T;i++)
f0(i);
return 0;
}
标签:const,int,KMP,++,ans,sf,define
From: https://www.cnblogs.com/2021sgy/p/16623889.html