KMP

这里写图片描述

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int nxt[10009],l1,l2;
char s1[100009],s2[10009];
void next_make()//求nxt数组
{
    int t1=0,t2=-1;
    nxt[0]=-1;
    while(t1<l2)
    {
        if(t2==-1||s2[t1]==s2[t1])
        {
            nxt[++t1]=++t2;
        }
        else t2=nxt[t2];
    }
}
void match(int t1,int t2)
{
    while(t1<l1&&t2<l2)
    {
        if(t2==-1||s2[t2]==s1[t1])
          t1++,t2++;
        else 
          t2=nxt[t2];       
    }
    if(t2==l2)
    {
        printf("YES
");
        return;
    }
    printf("NO
");
    return;
}
int main()
{
    gets(s1);gets(s2);
    l1=strlen(s1);
    l2=strlen(s2);
    next_make();
    match(0,0);
    return 0;
} 
原文地址:https://www.cnblogs.com/dfsac/p/6819732.html