跳到正文

个人记录

kmp模板

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
string s,p;
int next[10010],lenp,lens;
void work()
{
	next[0]=-1;
	int t=-1;
	for(int k=0;k<lenp-1;k++)
	{
		while(t!=-1&&p[t]!=p[k]) t=next[t];
		if(p[k+1]==p[t+1]) next[k+1]=next[t+1];
		else next[k+1]=t+1;
		t++;
	}
}
int main()
{
	cin>>s>>p;
	lens=s.length(),lenp=p.length();
	work();
	int i=0,j=0;
	for(;i<lens,j<lenp;)
	{
		if(s[i]==p[j]||j==-1) i++,j++;
		else j=next[j];
	}
	if(j==lenp) cout<<i-j+1;
	else cout<<-1;
	return 0;
}

不知道有没有错误

原文