当前位置:网站首页>[KMP] template

[KMP] template

2022-07-06 07:39:00 Code chess

s For longer strings to match
p It is a pattern string with small length
ne[i]: Indicates that in the pattern string i The length of the longest common prefix with subscript as the end point
j: Always represents the end position that can match the common pre suffix

Be careful :ne[1]=0, therefore i from 2 Start

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;

char s[N], p[N];
int ne[N];

int main()
{
    
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int n, m;
	cin >> n >> m;
	
	cin >> s + 1 >> p + 1;
	for(int i = 2, j = 0; i <= m; i++)
	{
    
		while(j && s[i] != s[j + 1]) j = ne[j];
		if(p[i] == p[j + 1]) j++;
		ne[i] = j;
	}
	
	for(int i = 1, j = 0; i <= n; i++)
	{
    
		while(j && s[i] != p[j + 1]) j = ne[j];
		if(s[i] == p[j + 1]) j++;
		if(j == m) j = ne[j]; // The match is successful  
	}
	return 0;
}

原网站

版权声明
本文为[Code chess]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131908419541.html