跳到正文

个人记录

KMP

mattinas约 2 分钟
原文
文章信息与版本

文章信息

发布
2021年8月9日
收录
2026年9月24日
更新
2026年11月3日
篇幅
约 2 分钟

版本

  1. v1当前

kmp一直是我困扰很久的,应该由于我不适合学信息学吧

参考博客

终于基本理解了它全部的思路与正确性之类的问题。。。就是在匹配串与文本串出现不同的,只移动匹配串,使得最大优化,移动规则就是目前已匹配部分的前后缀最大长度,这个最大长度代换到指针位置就是直接移到从开始到那个位置可以直接匹配的,不需要重新匹配的长度。大大优化……(写得我自己都蒙了)

模板题

C++
#include<bits/stdc++.h>
using namespace std;
char s1[1000001];
char s2[1000001];
int next[1000001];
int t,l;
void getnext()
{
	int i=-1,j=0;//前缀与后缀 
	next[0]=-1;
	while(j<l)
	{
		if(i==-1||s2[i]==s2[j])
		{
			i++;j++;
			next[j]=i;
		}
		else i=next[i];
	}
}
int main()
{
//	freopen("1.in","r",stdin);
//	freopen("1.out","w",stdout); 
	scanf("%s%s",s1,s2);
	t=strlen(s1);
	l=strlen(s2);
	getnext();int i=0,j=0;
	while(i<t)
	{
		if(j==-1||s1[i]==s2[j])
		{
			i++,j++;
			
		}
		else j=next[j];
		if(j==l)
		{
			printf("%d\n",i-j+1);
		}
	}
	for(int i=1;i<=l;i++)printf("%d ",next[i]);
	return 0;
}
原文
抓取于
  1. tigerhan7

    确实挺不错的

  2. mattinas

    淦啊你咋来给我评论了T^T

  3. Bluebird_

    我还是不理解TT