字符串匹配KMP算法,小心网上很多算法都有bug

最近网上看KMP算法,看了很多作者写的文章,后来发现看不明白,貌似哪里不正确,把代码拷下来运行发现也有问题,先举几个例子:

  1. https://www.cnblogs.com/yjiyjige/p/3263858.html

  2. 某人python代码

def kmp(string, match):
    n = len(string)
    m = len(match)
    i = 0
    k = 0
    count_times_used = 0
    while i < n:
        count_times_used += 1
        if match[k] == string[i]:
            if k == 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
            k += 1
        elif k > 0:
            k = j - 1
        else:
            i += 1

代码很简洁,但是输入:

kmp("abcdeffg", "abcdefg")

明显匹配不到,但是还是会得到结果。

拜读《算法导论》后,才将疑惑解除。

下面是正确的代码:

#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;
}


运行结果:

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

知识共享许可协议
本作品采用 知识共享署名-非商业性使用 4.0 国际许可协议进行许可。

转载于:https://my.oschina.net/wiiilll/blog/2874422

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值