其他分享
首页 > 其他分享> > 洛谷 P3375 【模板】KMP字符串匹配

洛谷 P3375 【模板】KMP字符串匹配

作者:互联网

地址 https://www.luogu.com.cn/problem/P3375

解法
KMP模板

#include<iostream>
#include<cstring>

using namespace std;
const int N = 1000010, M = 1000010;

int n, m;
int ne[N];
char s[M], p[N];

int main()
{
	std::cin >> (s + 1) >> (p + 1);
	int m = strlen(s+1);
	int n = strlen(p + 1);

	for (int i = 2, j = 0; i <= n; i++)
	{
		while (j && p[i] != p[j + 1]) j = ne[j];
		if (p[i] == p[j + 1]) j++;
		ne[i] = j;
	}

	for (int i = 1, j = 0; i <= m; i++)
	{
		while (j && s[i] != p[j + 1]) j = ne[j];
		if (s[i] == p[j + 1]) j++;
		if (j == n)
		{
			std::cout << i - n + 1 << std::endl;
			j = ne[j];
		}
	}
	for (int i = 1; i <= n; i++) {
		std::cout << ne[i] << " ";  
	}

	return 0;
}

我的视频题解空间

标签:std,1000010,include,洛谷,int,KMP,P3375,strlen
来源: https://www.cnblogs.com/itdef/p/15316556.html