kmp
点击查看代码
#include<bits/stdc++.h>
#define ll long long
#define fir first
#define sec second
#define pb push_back
#define pii pair<int,int>
#define mkp make_pair
#define db double
#define ls (x<<1)
#define rs (x<<1|1)
using namespace std;
void read(int &x){
char ch;int f=1;
while(!isdigit(ch=getchar())) if(ch=='-') f=-1;
x=ch-'0';
while(isdigit(ch=getchar())) x=(x<<1)+(x<<3)+ch-'0';
x*=f;
}
const int N=1e6+5;
char a[N],b[N];
int n,m;
int nt[N];
vector<int> ans;
void pre(){
int j=0;
for(int i=2;i<=m;i++){
while(j>0 && b[j+1]!=b[i]) j=nt[j];
if(b[j+1]==b[i]) j++;
nt[i]=j;
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
cin>>(a+1)>>(b+1);
n=strlen(a+1);m=strlen(b+1);
pre();
int j=0;
for(int i=1;i<=n;i++){
while(j>0 && b[j+1]!=a[i]) j=nt[j];
if(b[j+1]==a[i]) j++;
if(j==m) ans.pb(i-m+1),j=nt[j];
}
return 0;
}