复习KMP

2017.4.7:

看了好几遍的kmp,又忘了。。。

这次的理解:求next数组,求模式串的对称性(前缀和后缀的最大公共长度),next[i]表示模式串mo[1--i]这个子串的前缀和后缀的最大公共长度。

 


 

给这个月凑够20篇博客,手撸以便KMP,也当作温习一下。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

char N[1005],M[1005],lenN,lenM;
int next[1005];

void getNext()
{
    int p=0;
    for(int i=2;i<=lenM;i++)
    {
        while(p>0&&M[p+1]!=M[i])
            p=next[p];
        if(M[p+1]==M[i])
            p++;
        next[i]=p;
    }
}

bool KMP()
{
    getNext();
    cout<<"*"<<endl;
    int p=0;
    for(int i=1;i<=lenN;i++)
    {
        while(p>0&&M[p+1]!=N[i])
            p=next[p];
        if(M[p+1]==N[i])
            p++;
        if(p==lenM)
            return 1;
    }
    return 0;
}

int main()
{
    scanf("%s%s",N+1,M+1);
    lenN=strlen(N+1);
    lenM=strlen(M+1);
    cout<<KMP()<<endl;
    for(int i=1;i<=lenM;i++)
        cout<<next[i]<<" ";
    cout<<endl;
    return 0;
}

 

posted on 2017-02-28 16:30  JASONlee3  阅读(266)  评论(0编辑  收藏  举报

导航