克努斯-莫里斯-普拉特算法(Knuth–Morris–Pratt algorithm) c简单实现

本文介绍了著名的KMP字符串匹配算法,通过一个简单的C语言实现进行讲解。首先概述了算法的基本思想,然后详细解析了如何生成部分匹配表,并利用该表处理匹配失败时的偏移问题。
摘要由CSDN通过智能技术生成

偶尔看到的大名鼎鼎的KMP算法。
wiki在此

int kmp_search(char *needle, char *haystack) {
    if(NULL==haystack || NULL==needle)
        return -1;

    int nl=strlen(needle);
    int *failtable= (int *)malloc(nl*sizeof(int));
    if(NULL==failtable)
        exit(-1);

    //fail table
    char *p=needle;
    char *pn=needle+1;
    failtable[0]=-1;
    int pos=0;
    while(0!=*pn){
        failtable[pn-needle]=pos;
        if(*p==*pn){
            ++pos;
            ++p;
        }else{
            pos=0;
            p=needle;
        }
        ++pn;
    }

    //finding
    p=haystack;
    pn=needle;
    int ret=-1;
    while(0!=*p){
        while(*p==*pn && 0!=*p){
            ++p;
            ++pn;
        }
        if(0==*pn){
            //found
            ret=(p-haystack)-nl;
            break;
        }
        //no chance to find
        if(0==*p)
            break;

        //differ
        pos=failtable[pn-needle];
        if(-1==pos){
            ++p;
        }else{
            pn=needle+pos;
        }
    }

    free(failtable);

    return ret;
}

int main(){
    char h[] = "ABC ABCDAB ABCDABCDABDE";

    int ret = kmp_search("ABCDABD",h);

    printf("ret:%d\n",ret);
}

以上是我根据wiki 的例子写的一个实现。
主要就是先扫目标串,生成部分匹配表,然后根据表来处理匹配失败的偏移。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值