样例和数据1都过了但是还是WA了
查看原帖
样例和数据1都过了但是还是WA了
64199
EternalArthorn楼主2021/8/23 19:01
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e6+9;
int n,m;
int next[MAX_N];  // 存能够匹配上的前一个字符串最后面的 位置 
void makenext(string a)
{
	int temp;
	next[0]=-1;// 初始化 
	for(int i=1;i<=m;i++)
	{
		temp=next[i-1];   //temp为数组下标指针 
		while(temp>=0&&a[temp+1]!=a[i])
		{
			temp=next[temp];  // 指针回溯 
		}
		if(a[temp+1]==a[i])
		{
			next[i]=temp+1;
		}
		else
		{
			next[i]=-1;
		}
	}
	return ;
}
void kmp(string s,string p)
{
	int i,j;
	if(m>n) return ;
	makenext(p);
	while(i<=n&&j<=m)
	{
		if(j==m&&s[i]==p[j])
		{
//			cout<<i-m<<endl;  // wrong
			printf("%d\n",i-m+1);
			i=i-m+1;
			j=0;
		}
		if(s[i]==p[j])
		{
			i++,j++;
		}
		else if(j>0)
		{
			j=next[j-1]+1;
		}
		else 
		{
			i++;
		}
	}
	return ;
}
int main()
{
	string s,p;
	cin>>s;
	cin>>p;
	n=s.length()-1;
	m=p.length()-1;    //n,m 分别记录数组最后一个的下标 
//	cout<<n<<"     "<<m<<endl;
	kmp(s,p);
	for(int i=0;i<=m;i++)
	{
//		cout<<next[i]+1<<" "; 
		printf("%d ",next[i]+1);
	}
	return 0;
}
2021/8/23 19:01
加载中...