KMP 算法

//参考算法导论

#include <string.h>

#include <stdio.h>

// 前缀函数
int *compute_prefix_function(const char *needle)
{
    int len = strlen(needle);
    int *c = new int[len];
    memset(c, 0, len * sizeof(int));
    c[0] = 0;
    int k = 0;

    for(int q = 2; q <= len; ++q)
    {
        while(k > 0 && needle[k] != needle[q - 1]) {
            k = c[k - 1];
        }
        if(needle[k] == needle[q - 1]) {
            ++k;
        }
        c[q - 1] = k;
    }
    printf("the value of prefix function array:\n");
    for (int i = 0; i < len; ++i) {
        printf("%6d", c[i]);
    }
    printf("\n");
    return c;
}

void kmp_matcher(const char *haystack, const char *needle)
{
    int n = strlen(haystack);
    int m = strlen(needle);
    int *c = new int[m];
    memset(c, 0, m * sizeof(int));

    c = compute_prefix_function(needle);
    int q = 0;
    for(int i = 1; i <= n; i++)
    {
        while(q > 0 && needle[q] != haystack[i - 1]) {
            q = c[q - 1];
        }
        if(needle[q] == haystack[i - 1]) {
            q = q + 1;
        }
        if(q == m)
        {
            printf("Pattern occurs with shift %d \n",i-m+1);
            q = c[q - 1];
        }
    }
}

int main()
{
    const char * haystack = "bacbababaabcbab";
    const char * needle = "ababa";
    printf("haystack = %s\n  needle = %s\n", haystack, needle);
    kmp_matcher(haystack, needle);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值