【模板】KMP

/*判断字符串b是否是a的字串*/

#include
using namespace std;
void GetNext(const char *p, int *next)
{
	next[0] = -1;
	next[1] = 0;

	int j = 1;
	int k = 0;
	int lenp = strlen(p);

	while (j + 1 < lenp)
	{
		if (k == -1 || p[k] == p[j])
		{
			next[++j] = ++k;
		}
		else
		{
			k = next[k];
		}
	}
}
int KMP(const char *s, const char *p, int pos)
{
	assert(s != NULL && p != NULL);

	int lens = strlen(s);
	int lenp = strlen(p);

	if (lens < lenp)
	{
		return -1;
	}

	int i = pos;
	int j = 0;
	int *next = (int *)malloc(sizeof(int) * lenp);
	assert(next != NULL);

	GetNext(p, next);

	while (i < lens && j < lenp)
	{
		if (j == -1 || s[i] == p[j])
		{
			i++;
			j++;
		}
		else
		{
			j = next[j];
		}
	}

	free(next);

	if (j >= lenp)
	{
		return i - j;
	}

	return -1;
}
char a[100000+10],b[100000+10];
int main()
{
    scanf("%s",a);
    scanf("%s",b);
    int ans=KMP(a,b,0);
    if(ans!=-1) printf("YES\n");
    else printf("NO\n");
}

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