KMP算法实现

#include <QCoreApplication>
#include<iostream>
using namespace std;

void creatNext(char* p,int plen,int *next)
{
    next[0]=-1;
    for(int i=0,j=-1;i<plen;i++)
    {
        if(j==-1||p[i]==p[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else
        {
            j=next[j];
        }
    }
}

bool KMP(char* s,int slen,char* p,int plen,int* pos)
{
    int next[100]={0};
    creatNext(p,plen,next);
    int i=0;
    int k=0;

    while(k<plen&&i<slen)
    {
        if(k==-1||s[i]==p[k])
        {
            i++;
            k++;
        }
        else
        {
            k=next[k];
        }
    }
    if(k==plen)
    {
        *pos=i-plen+1;
        return 1;
    }
    else
    {
        return 0;
    }

}


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    char A[]="abcfbtrchgcabfk";
    char B[]="trc";
    int slen=strlen(A);
    int plen=strlen(B);
    int pos=0;
    if(KMP(A,slen,B,plen,&pos))
    {
        cout<<"find pos:"<<pos<<endl;
    }
    else
    {
        cout<<"fail"<<endl;
    }

    return a.exec();
}

你可能感兴趣的:(KMP算法实现)