1、KMP
KMP模板
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#define ll long long
#define INF 2147483647
#define mem(i,j) memset(i,j,sizeof(i))
#define F(i,j,n) for(register int i=j;i<=n;i++)
using namespace std;
char s1[1000010],s2[1000010];
int Next[1000010],l1,l2;
inline int read(){
int datta=0;char chchc=getchar();bool okoko=0;
while(chchc<'0'||chchc>'9'){if(chchc=='-')okoko=1;chchc=getchar();}
while(chchc>='0'&&chchc<='9'){datta=datta*10+chchc-'0';chchc=getchar();}
if(okoko==1)return -datta;return datta;
}
inline void get_Next(){
int j=0;
F(i,1,l2){
while(j&&s2[j+1]!=s2[i+1])
j=Next[j];
if(s2[j+1]==s2[i+1])
j++;
Next[i+1]=j;
}
}
inline void kmp(){
int j=0;
F(i,1,l1){
while(j&&s2[j+1]!=s1[i])
j=Next[j];
if(s2[j+1]==s1[i])
j++;
if(j==l2){
printf("%d\n",i-j+1);
j=Next[j];
}
}
}
int main(){
scanf("%s%s",s1+1,s2+1);
l1=strlen(s1+1);l2=strlen(s2+1);
get_Next();
kmp();
F(i,1,l2-1)
printf("%d ",Next[i]);
printf("%d\n",Next[l2]);
return 0;
}
原文地址:https://www.cnblogs.com/hzf29721/p/10223108.html
时间: 2024-10-08 15:56:37