對於暴力搜尋法,當搜尋詞對應的字元與字串中的字元不匹配時。將搜尋詞整個後移一位,再從頭逐個比較。這樣做雖然可行,但是效率很差,因為你要把”搜尋位置”移到已經比較過的位置,重比一遍。

應用KMP演算法之後,則有:
=
KMP演算法
“部分匹配值”就是”字首”和”字尾”的最長的共有元素的長度。

KMP演算法實現程式碼如下

void prefixFun(char *pattern, int *preFun)
{
    int len = 0; //length of pattern
    while ('\0' != pattern[len])
        len++;

    int LOLP = 0; //length of longest prefix
    preFun[1] = 0;
    for (int NOCM = 2; NOCM <= len; NOCM++) //NOCM : number of characters matched
    {
        while (LOLP > 0 && pattern[LOLP] != pattern[NOCM-1])
            LOLP = preFun[LOLP];
        if (pattern[LOLP] == pattern[NOCM-1])
            LOLP++;
        preFun[NOCM] = LOLP;
    }
}

void KMPstrMatching(char *target, char *pattern)
{
    int tarLen = 0;
    int patLen = 0;
    while ('\0' != target[tarLen])
        tarLen++;
    while ('\0' != pattern[patLen])
        patLen++;

    int *preFun = new int[patLen+1];
    prefixFun(pattern, preFun);

    int NOCM = 0; // number of characters matched

    for (int i = 0; i < tarLen; i++)
    {
        while (NOCM > 0 && pattern[NOCM] != target[i])
            NOCM = preFun[NOCM];
        if (pattern[NOCM] == target[i])
            NOCM++;

        if (NOCM == patLen)
        {
            cout<<"Pattern occurs with shift "<<i - patLen + 1<<endl;
            NOCM = preFun[NOCM];
        }
    }

    delete [] preFun;
}