字符串匹配KMP算法最正確算法,網上不少算法都有bug,致使誤導不少人

最近網上看KMP算法,看了不少做者寫的文章,後來發現看不明白,貌似哪裏不正確,把代碼拷下來運行發現也有問題,致使誤導了不少人,我先舉幾個例子:html

  1. https://www.cnblogs.com/yjiyj...
  2. 某人python代碼
def kmp(string, match):
    n = len(string)
    m = len(match)
    i = 0
    j = 0
    count_times_used = 0
    while i < n:
        count_times_used += 1
        if match[j] == string[i]:
            if j == m - 1:
                print "Found '%s' start at string '%s' %s index position, find use times: %s" % (match, string, i - m + 1, count_times_used,)
                return
            i += 1
            j += 1
        elif j > 0:
            j = j - 1
        else:
            i += 1

代碼很簡潔,可是輸入:python

kmp("abcdeffg", "abcdefg")

明顯匹配不到,可是仍是會獲得結果。算法

拜讀《算法導論》後,纔將疑惑解除。code

下面是正確的代碼:htm

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LEN 100

int * getnext(const char * pattern);

int main()
{
        char string[MAX_LEN];
        char pattern[MAX_LEN];

        int *next;

        scanf("%s", string);
        scanf("%s", pattern);

        int slen = strlen(string);
        int plen = strlen(pattern);

        if(plen > slen || slen > MAX_LEN || plen > MAX_LEN)
        {
                exit(0);
        }

        next = getnext(string);

        int q = -1;

        for(int i = 0; i < slen; i++)
        {
                while(q >= 0 && pattern[q+1] != string[i])
                {
                        q = next[q];

                }
                if(pattern[q+1] == string[i])
                {
                        q++;
                }
                if(q == plen - 1)
                {
                        printf("pattern occurs with shift %d\n", i + 1 - plen);
                        q = next[q];
                }
        }

        return 1;
}

int * getnext(const char * pattern)
{
        int plen = strlen(pattern);

        int *next = (int *)malloc(MAX_LEN * sizeof(int));

        next[0] = -1;

        int k = -1;

        for(int j = 1; j < plen; ++j)
        {

                while(k >= 0 && pattern[j] != pattern[k+1])
                {
                        k = next[k];
                }

                if(pattern[k+1] == pattern[j])
                {
                        k++;
                }

                next[j] = k;
        }

        return next;
}

運行結果:blog

abcdefghijkkkkkkkkkllllll
k
pattern occurs with shift 10
pattern occurs with shift 11
pattern occurs with shift 12
pattern occurs with shift 13
pattern occurs with shift 14
pattern occurs with shift 15
pattern occurs with shift 16
pattern occurs with shift 17
pattern occurs with shift 18
相關文章
相關標籤/搜索