一篇文章帶你瞭解C++的KMP算法

KMP算法

KMP算法作用:字符串匹配

例如母串S = “aaagoogleaaa”;

子串T= “google”;

步驟1:先計算子串中的前後綴數組Next

g o o g l e
next[0] next[1] next[2] next[3] next[4] next[5]
-1 0 0 0 1 0

C++代碼:

//步驟1:
void GetNext(string Tsub, vector<int>& Next)
{
    int j = 0, k = -1;
    Next[0] = k;
    while (j < Tsub.length() - 1)
    {
        if (k == -1 || Tsub[j] == Tsub[k])
        {
            Next[++j] = ++k;
        }
        else
        {
            k = Next[k];
        }
    }
}

步驟2:查找子串在母串中出現的位置。

//步驟2:
int KMP(string S, string T, vector<int> Next)
{
    int i = 0, j = 0;
    int m = S.length();
    int n = T.length();
    while (i < m && j < n)
    {
        if (j == -1 || S[i] == T[j])
        {
            i++;
            j++;
        }
        else
        {
            j = Next[j];
        }
    }
    if (j == n)
    {
        return i - j;
    }
    else
    {
        return -1;
    }
}

結合上面兩個步驟寫出完整代碼:

#include <iostream>
#include <vector>
using namespace std;
//步驟1:
void GetNext(string Tsub, vector<int>& Next)
{
    int j = 0, k = -1;
    Next[0] = k;
    while (j < Tsub.length() - 1)
    {
        if (k == -1 || Tsub[j] == Tsub[k])
        {
            Next[++j] = ++k;
        }
        else
        {
            k = Next[k];
        }
    }
}
//步驟2:
int KMP(string S, string T, vector<int> Next)
{
    int i = 0, j = 0;
    int m = S.length();
    int n = T.length();
    while (i < m && j < n)
    {
        if (j == -1 || S[i] == T[j])
        {
            i++;
            j++;
        }
        else
        {
            j = Next[j];
        }
    }
    if (j == n)
    {
        return i - j;
    }
    else
    {
        return -1;
    }
}
int main()
{
    string S = "aaagoogleaaa";
    string T = "google";
    vector<int> Next(T.length());
    GetNext(T, Next);
    int retVal = KMP(S, T, Next);
    if (retVal == -1)
    {
        std::cout << "can't Index" << std::endl;
    }
    else
    {
        std::cout << "Index :" << retVal << std::endl;
    }
    return 0;
}

總結

本篇文章就到這裡瞭,希望能給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: