KMP 详解+模板

详解

#include
#include
#include 
#include 
#include
using namespace std;

int next[1000],num=0;
void GetNextval(char* p, int next[])
{
	int pLen = strlen(p);
	next[0] = -1;
	int k = -1;
	int j = 0;
	while (j < pLen - 1)
	{
		if (k == -1 || p[j] == p[k])
		{
			j++;k++;
			if (p[j] != p[k])
				next[j] = k;
			else
				next[j] = next[k];
		}
		else
		{
			k = next[k];
		}
	}
}
int KmpSearch(char* s, char* p)
{
	int i = 0,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;
}
int main()
{
    char a[1000],b[1000];
    while(~scanf("%s %s",a,b))
    {
        GetNextval(b,next);
        cout<

 

你可能感兴趣的:(模板,字符串,算法)