KMP解释+原理

KMP算法—字符串匹配、查找子串。

1.优点:非常快

2.视频解析地址(本人认为这个up主讲的很好,肯定能看懂,一共分两期。一期讲原理,一期讲代码):

小破站传送门1

小破站传送门2

3.力扣上的第28题可以用此方法解决,当然也可以用编程语言的内置函数。但刷题难道不是为了学习算法么?以下是我根据这个up主的代码,写的java代码:
class Solution {
    public int strStr(String haystack, String needle) {
        int res=0;
        char [] text=haystack.toCharArray();
        char [] pattern=needle.toCharArray();
        if (needle.length()==0){
            return 0;
        }
        res=Kmp_search(text,pattern);
        return res;
    }

    public void next_table(char [] pattern,int [] next,int n){
        next[0]=0;
        int len=0;
        int i=1;
        while (i<n){
            if (pattern[i]==pattern[len]){
                len++;
                next[i]=len;
                i++;
            }else {
                if (len>0){
                    len=next[len-1];
                }else {
                    next[i]=len;
                    i++;
                }
            }
        }

    }
    public  void mov_next(int [] next,int n){
        for (int i=n-1;i>0;i--){
            next[i] = next[i-1];
        }
        next[0]=-1;
    }

    public int Kmp_search(char [] text,char [] pattern){
        int n=pattern.length;
        int m=text.length;
        int [] next=new int[n];
        int res=-1;
        next_table(pattern,next,n);
        mov_next(next,n);//得到处理后的next数组

        int j=0,i=0;
        while (i<m){
            if (j==n-1 && text[i]==pattern[j]){
                res=i-j;
                j=next[j];
                return res;
            }
            if (text[i]==pattern[j]){
                i++;j++;
            }else {
                j=next[j];
                if (j==-1){
                    i++;
                    j++;
                }
            }
        }
        return res;

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值