【算法模板】KMP(关键在于next数组的理解和灵活运用)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43238423/article/details/102556662
#include<bits/stdc++.h>
using namespace std;
int Next[1000];
int Kmp_Search(char* s, char* p)
{
	int i = 0;
	int j = 0;
	int sLen = strlen(s);
	int pLen = strlen(p);
	while (i < sLen && j < pLen)
	{
		if (j == -1 || s[i] == p[j])
		{
			i++;
			j++;
		}
		else
		{
			j = Next[j];
		}
	}
	if (j == pLen)
		return i - j;
	else
		return -1;
}
void Get_Next(char* p,int* next)
{
	int pLen = strlen(p);
	next[0] = -1;
	int k = -1;
	 int j = 0;// ABCDABD
	while (j < pLen - 1){
		if (k == -1 || p[j] == p[k]){
			++k;
			++j;
			next[j]=k;
		}
		else k = next[k];
	}
}
int main()
{
    

}

猜你喜欢

转载自blog.csdn.net/weixin_43238423/article/details/102556662