KMP算法实现

在brute force的字符串匹配中,每次失败后,都要从模式串的第一位开始比较,没有利用到上一次比较中的信息。KMP则是通过对模式串的预处理,匹配过程中,一旦失败,则利用上一次的匹配的结果,不用从模式串的第一位开始比较,从而达到最坏情况下复杂度为线性。

#include<stdio.h>
#define MAX 100
void corresponding(int*,char*);
int index_KMP(char*,char*);
int main()
{
     char str_pattern[]="kaka";
     char str_src[]="idddddddamkaka";
     printf("%d/n",index_KMP(str_src, str_pattern));
     getch();
     return 0;
}
int index_KMP(char *src,char *pat)
{
    int next[MAX],pot=0;
    char *base = src,*rear = pat;
    corresponding(next,pat);
    for(;*src;)
    {   pot = src - base;
        for(;*pat && *src && *src==*pat;src++,pat++);
        if(!*pat)return pot;
        if(pat>rear){
        pat = rear + next[pat-rear-1];
        }
        else
        {
         src++;
         pat = rear;
        }
       
    }
    return -1;
}
void corresponding(int *p,char *ps)
{
     int i,k=0;
     for(p[0] = 0,i=1;ps[i];p[i] = k= 0,i++)
        for(;ps[i] && ps[k]==ps[i];i++,k++)p[i] = k+1;
}

 

模式匹配算法其实很简单

例如: a   b   a   b   c   a    b

可以这样比较

    b   a   b   c   a    b

    a   b   a   b   c   a    b

如果上下完全匹配那就确认了 a   b   a   b   c   a    b 每一个匹配值

 

    a   b   c   a    b

    a   b   a   b   c   a    b

-----------------------------------------------

     b   c   a    b

    a   b   a   b   c   a    b

------------------------------------------------

     c   a    b

    a   b   a   b   c   a    b

-----------------------------------------------------

    a    b

    a   b   a   b   c   a    b

--------------------------------------------------------

    b

    a   b   a   b   c   a    b

一次每一个值就会确定

利用这个算法也可以求得 第一个最大重复子串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值