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

地址 https://www.luogu.com.cn/problem/P3375
洛谷 P3375 【模板】KMP字符串匹配

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

我的视频题解空间

上一篇:Java基本数据类型的输入输出


下一篇:分块,单调栈--Water Balance