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;
}

我的视频题解空间

posted on 2021-09-21 14:29  itdef  阅读(30)  评论(0编辑  收藏  举报

导航