题解 P3375 【【模板】KMP字符串匹配】(KMP学习笔记)

题目link
qwq

Code

#include<bits/stdc++.h>
using namespace std;
int P[1000010];
int la,lb,st,en;
char sa[1000010],sb[1000010];
int main()
{
	cin>>sa+1>>sb+1;
	la=strlen(sa+1);
	lb=strlen(sb+1);
	P[1]=0;
	for(int i=2;i<=lb;i++)
	{
		int now=P[i-1];
		while(now>0&&sb[i]!=sb[now+1])
		{
			now=P[now];
		}
		if(sb[i]==sb[now+1])
		{
			P[i]=now+1;
		}
		else
		{
			P[i]=0;
		}
	}
	int now=0;
	for(int i=1;i<=la;i++)
	{
		while(now>0&&sa[i]!=sb[now+1])
		{
			now=P[now];
		}
		if(sa[i]==sb[now+1])
		{
			now++;
		}
		if(now==lb)
		{
			cout<<i-lb+1<<endl;
			now=P[now];
		}
	}
	for(int i=1;i<=lb;i++)
	{
		cout<<P[i]<<" ";
	}
} 
posted @ 2019-05-10 20:31  G_A_TS  阅读(558)  评论(3编辑  收藏  举报