跳到正文

个人记录

最短KMP

Chenyj29约 1 分钟
原文
文章信息与版本

文章信息

发布
2021年12月31日
收录
2025年12月12日
更新
2026年11月7日
篇幅
约 1 分钟
获赞
2

版本

  1. v1当前

最短KMP,只有一层循环

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
char s[N], t[N];
int Next[N];

int main(){
	scanf("%s%s", s, t);
	int lens=strlen(s), lent=strlen(t);
	Next[0]=-1;
	for(int i=1,j=0;i<=lent;)
		if(j==-1 || t[j]==t[i]) Next[++i] = ++j;
		else j=Next[j];
	
	for(int i=0,j=0;i<=lens-lent;)
		if(j==-1 || j<lent && s[i+j]==t[j]) ++j;
		else {
			if(j==lent) printf("%d\n", i+1);
			i=i+j-(j=Next[j]);
		}
	for(int i=1;i<=lent;++i) printf("%d ", Next[i]);
	return 0;
}
原文
抓取于
  1. logZ

    # a

  2. logZ

    老师nb

  3. logZ

    qp