KMP

KMP

标签(空格分隔): Data-Structure


照着金叔课本来的,因为看了其他各种版本,各种混乱

8.15 普通解法

#include <iostream>
#include <cstring>

using namespace std;

//textbook, the regular solution
void getNext(const char *s, int next[])
{
    int len = strlen(s);
    int j = 1,i = -1;
    next[0] = -1;
    while(j < len){
        i = next[j-1];
        while((i>=0) && (s[j]!=s[i+1]))
            i = next[i];

        if(s[j] == s[i+1])
            next[j] = i+1;
        else
            next[j] = -1;

        j++;
    }
}

int Find(const char *s, const char *pat, int next[])
{
    int i = 0, j = 0;
    int lenS = strlen(s), lenP = strlen(pat);
    cout<<lenS<<" "<<lenP<<endl;
    while((j < lenP) && (i < lenS)){//bug 写成了 i < lenS - lenP + 1
        if(s[i] == pat[j]){
            i++;
            j++;
        }
        else if(j == 0)
            i++;
        else{
            j = next[j-1] + 1;
        }
    }
    if(j <lenP || lenP == 0)
        return -1;
    else
        return (i - lenP);//完全匹配后 i 位于母串中子串序列的最后一个下标+1的位置

}
/* another book, tend to abandon
//void getNext(const char *s, int next[])
//{
//    int i = 0, j= -1;
//    next[0] = -1;
//    int len = strlen(s);
//    while(i < len){
//        if(j == -1 || s[i] == s[j])
//        {
//            ++i;
//            ++j;
//            next[i] = j;
//        }
//        else
//            j = next[j];
//    }
//} */
int main()
{
    const char *pat = "abcabcacab";
    const char *s = "abcdabceabcabcacab";
    int lengthP = strlen(s);
    //cout<<length<<endl;
    int next[lengthP];
    for(int i = 0; i<lengthP; i++)
    {
        next[i]=0;
        //cout<<next[i]<<" ";
    }
    getNext(s,next);
//    for(int i = 0; i<length; i++)
//    {
//        cout<<next[i]<<" ";
//    }
    cout<<Find(s, pat, next)<<endl;
    return 0;
}

还有改进的失败函数

转载于:https://www.cnblogs.com/Haeckel/p/3916042.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值