本地通过,提交CE
查看原帖
本地通过,提交CE
47911
xiaozhangma楼主2022/10/21 22:51
#include<bits/stdc++.h>
using namespace std;
int read(){
    int x=0,f=1;
    char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
const int N = 1e6 + 10;
int next[N],len1,len2;//next[j]表示S[i]!=T[j]时,j需要回退的位置 
char S[N],T[N];
void pre(){
	int j = 0,k = -1;
	next[0] = -1;//初始化 
	while(j < len2){
		if(k == -1 || T[k] == T[j]){
			if(T[++k] == T[++j]){
				next[j] = next[k+1];
			}else{
				next[j] = k;
			}
		}else{
			k = next[k];
		}
	}
}
void KMP(){
	int i = 0, j = 0;
	while(i<len1){
		if(j == -1 || S[i] == T[j]){
			i++,j++;
		}else{
			j = next[j];//回退 
		}
		if(j == len2)printf("%d\n",i-len2+1),j = next[j];
	}
	
}
int main(){
	scanf("%s%s",S,T);
	
	len1 = strlen(S);
	len2 = strlen(T);
	pre();
	KMP();
	
	for(int i = 1; i <= len2; i++)printf("%d ",next[i]);
	puts("");
	
	return 0;
}

CE

2022/10/21 22:51
加载中...