字符串 匹配 KMP算法

/***************************************************
*  函数功能:字符串 匹配
*  参数说明
*       输入参数:  string str  = "abcabcababaccc";
                    string match = "ababa";
*       输出参数:6
*  复杂性分析:时间复杂度:O(N),空间复杂度:O(N)
*  题目来源  :
*  作者:guoliang zheng
*  日期:2018-08-17-14.45
***************************************************/
int KMP::getIndexOf(string str,string match)
{
    if(str.size()<1 || match.size()<1 || str.size()<match.size()) return -1;
    int lenstr=str.size();
    int lenmat=match.size();
    vector<int> next=getNextArray(match);
    int si=0;
    int mi=0;
    while(si<str.size() && mi<match.size())
    {
        if(str[si]==match[mi])
        {
            si++;
            mi++;
        }else if(next[mi]==-1)
        {
            si++;
        }else
        {
            mi=next[mi];
        }
    }
    return mi==match.size()?si-mi:-1;
}

vector<int> KMP::getNextArray(string match)
{
    if(match.size()==1)
    {
        vector<int> Next(1,-1);
        return Next;
    }
    int len=match.size();
    vector<int> Next(len,0);
    Next[0]=-1;
    Next[1]=0;
    int cn=0;
    int pos=2;
    while(pos<len)
    {
        if(match[pos-1]==match[cn])
        {
            Next[pos++]=++cn;
        }else if(cn>0)
        {
            cn=Next[cn];
        }else
        {
            Next[pos++]=0;
        }
    }
    return Next;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值