您的位置:首页 > 其它

KMP模板

2016-10-25 14:40 183 查看
O(n+m)时间复杂读的kmp 

#include<iostream>

#include<cstdio>

#include<algorithm>

#include<cstring>

using namespace std;

char a[1005],b[1005];

int next[1005];

void getnext(int bl)            //next数组

{   next[0]=-1;

    int i=0,j=-1;

    while(i<bl)

   {if(j==-1||b[i]==b[j])

    {

        i++;j++;

        if(b[i]==b[j])

            next[i]=next[j];

        else

            next[i]=j;

    }

    else j=next[j];

    }

}

int kmp(int kal,int kbl)       //判断

{   getnext(kbl);

    int i=0,j=0;

    while(i<kal)

    {

        if(j==-1||a[i]==b[j])

        {

            i++;j++;

        }

        else j=next[j];

        if(j==kbl)

            return 1;

    }

    return 0;

}

int main()

{  int n,k=0;

   scanf("%d",&n);

   cin.get();

   while(n--)

    {  k++;

    scanf("%s%s",a,b);

        int ans=kmp(strlen(a),strlen(b));

    if(ans==1)printf("Case #%d: Yes\n",k);

    else printf("Case #%d: No\n",k);

    }

    return 0;

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: