KMP算法小记

   public void getNext (char mainChr[], int next[]) {
       //构造next数组,参数mainChr[]是主元字符串
        next[0] = -1;
        int behind = 0, front = -1;

        //front指向前缀,back指向后缀
        while (behind < mainChr.length) {
            if (front == -1 || mainChr[behind] == mainChr[front]) {
                behind++;
                front++;
                next[behind] = front;
            } else { 
            //mainChr[behind] != mainChr[front],
            //找到之前已经计算过的next[front]继续计算当前字符串的最大前后缀的交集数
                front = next[front];
            }
        }
    }
    //若存在该子字串,返回该子字符串起始下标,否,返回-1
    public int KMP (char[] mainChr, char[] tarChr) {
        //参数mainChr是主元字符串,参数tarChr是子字符串。
        int mP = 0;
        int tP = 0;

        while (mP < mainChr.length && tP < tarChr.length) {
            if (tP == -1 || mainChr[mP] == tarChr[tP]) {
                mP++;
                tP++;
            } else {
                tP = next[tP];
            }
        }
        if (tP == tarChr.length)
            return mP-tP;
        else
            return -1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值