求C++ KMP算法-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

求C++ KMP算法

急求 KMP算法, C++ 语言

展开
收起
知与谁同 2018-07-18 16:29:07 2674 0
1 条回答
写回答
取消 提交回答
  • 阿里云开发者社区运营负责人。原云栖社区负责人。
    const vector<int> * kmp_next(string &m) // count the longest prefex string ;
    {
    static vector<int> next(m.size());
    next[0]=0; // the initialization of the next[0];

    int temp; // the key iterator......

    for(int i=1;i<next.size();i++)
    {
    temp=next[i-1];

    while(m[i]!=m[temp]&&temp>0)
    { temp=next[temp-1];
    }

    if(m[i]==m[temp])
    next[i]=temp+1;
    else next[i]=0;

    }

    return &next;

    }

    bool kmp_search(string text,string m,int &pos)
    {
    const vector<int> * next=kmp_next(m);

    int tp=0;
    int mp=0; // text pointer and match string pointer;

    for(tp=0;tp<text.size();tp++)
    {
    while(text[tp]!=m[mp]&&mp)
    mp=(*next)[mp-1];

    if(text[tp]==m[mp])
    mp++;

    if(mp==m.size())
    { pos=tp-mp+1;
    return true;
    }
    }

    if(tp==text.size())
    return false;
    }
    2019-07-17 22:55:54
    赞同 展开评论 打赏
问答分类:
问答地址:
相关产品:
问答排行榜
最热
最新
相关电子书
更多
阿里技术参考图册-算法篇
立即下载
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
相关实验场景
更多