KMP算法

KMP算法·
昨天花了一下午把KMP算法搞懂了,下面是代码

#include 
#include 
using namespace std;

void GetNext(string P, int next[])
{
    int len_p = P.size();
    int i = 0;
    int j = -1;
    next[0] = -1;
    while (i < len_p - 1)
    {
        if((-1 == j)|| (P[j] == P[i]))
        {
            j++;
            i++;
            next[i] = j;
        }
        else
            j = next[j];
    }
}

int KMP(string S, string P, int next[])
{
    GetNext(P, next);

    int i = 0;
    int j = 0;
    int len_s = S.size();
    int len_p = P.size();

    while (i < len_s && j < len_p)
    {
        if (j==-1 || S[i]==P[j] )      //next[0] = -1;
        {
            i++;
            j++;
        }
        else
            j = next[j];
    }

    if (len_p == j)
        return i - j;

    return -1;
}

int main()
{
    int Next[100] = { 0 };

    cout << KMP("sdsdsdsd", "dkm", Next) << endl;
    return 0;
}


你可能感兴趣的:(数据结构与算法)