跳到正文

个人记录

KMP学习笔记

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

文章信息

收录
2025年12月12日
更新
2026年2月28日
篇幅
约 2 分钟

版本

  1. v1当前

今天学习一种神奇的KMP的理解方式,因此写一篇学习笔记加强理解。

基本定义

对于字符串 aa 和 bb,我们定义 aa % bb 为:

  1. 满足字串 pp 为 aa 的后缀
  2. 满足字串 pp 为 bb 的前缀
  3. 字串 pp 是满足上述两条要求最长的字串

(其实就是正常KMP的 borderborder)

核心公式

定义 a+ba+b 为字串 aa 和 bb 的拼接。

得到公式 (a+b)%p=((a%p)+b)%p。

由于我太菜了所以只有一个漏洞很大的感性证明。

感性证明

考虑原运算类似于从后往前算贡献,因此在字串 aa 中有可能产生贡献的只有 a%p 的部分。

实现

记 append(s,c)=(p[0,s)+c) % p

如果确定答案一定不超过 ss 则最开始的一位可以去除。

因此考虑记 f(s)=(p[1,s)+c) % p

整理后容易得 append(s,c)=append(f(s),c)append(s,c)=append(f(s),c)

对于 f(i)f(i) 则有 f(i)=append(f(i−1),s[i−1])f(i)=append(f(i-1),s[i-1])

C++
#include<bits/stdc++.h>
using namespace std;
int f[1000010],n,m;
string a,b;
int append(int si,char c){
	if(si<m&&b[si]==c)
		return si+1;
	else if(si>0)
		return append(f[si],c);
	return 0;
}
int main(){
	cin>>b>>a;
	n=a.size(),m=b.size();
	f[1]=0;
	for(int i=1;i<m;i++)
		f[i+1]=append(f[i],b[i]);
	int si=0,ans;
	for(int i=0;i<n;i++){
		si=append(si,a[i]);
		if(si==m)
			ans++;
	}
	cout<<ans;
}
原文