day9| KMP算法

本文介绍了在LeetCode中如何使用KMP算法解决字符串查找问题,包括两种方法:一种是用于查找特定子串出现的位置,另一种是检测是否存在重复子串。KMP算法通过构建next数组优化了查找过程。
摘要由CSDN通过智能技术生成

真的很难,只是把原理记住了,这里默写一遍.KML算法在从一个字符串找某一字符串中是否出现的场景下经常应用。

28力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

1.用内置函数的方法:
 

class Solution {
    public int strStr(String haystack, String needle) {
        int left = 0;
        int right = needle.length()-1;
        while(right < haystack.length()){
            if(haystack.substring(left,right+1).equals(needle)){
                return left;
            }
            right++;
            left++;
        }

        return -1;
    }
}

2.用KMP算法

class Solution {
    public int strStr(String haystack, String needle) {
        int[] next = new int[needle.length()];
        int j = 0;
        nextBound(needle,next);
        for(int i = 0; i<haystack.length();i++){
            while(j > 0 && haystack.charAt(i) != needle.charAt(j)){
                j = next[j - 1];
            }
            if(haystack.charAt(i) == needle.charAt(j)){
                j++;
            }
            if(j == needle.length()){
                return (i - needle.length() + 1);
            }
        }
        return -1;
    }
    public void nextBound(String s,int[] next){
        int j = 0;
        next[0] = 0;
        for(int i = 1; i< s.length();i++){
            while(j > 0 && s.charAt(i) != s.charAt(j)){
                j = next[j - 1];
            }
            if(s.charAt(i) == s.charAt(j)){
                j++;
            }
            next[i] = j;
        }
    }
}

459.力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

方法一:KMP

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        int j = 0;
        int[] next = new int[s.length()];
        nextBound(s,next); 
        int len = s.length();
        int max = next[len - 1];
        if(max != 0 && len % (len - next[len - 1]) == 0){
            return true;
        }
        return false;
    }
    public void nextBound(String s,int[] next){
        int j = 0;
        next[0] = 0;
        for(int i = 1; i< s.length();i++){
             while(j > 0 && s.charAt(j) != s.charAt(i)){
                 j = next[j - 1];
             }
             if(s.charAt(j) == s.charAt(i)){
                 j++;
             }
             next[i] = j;
        }
    }
}

方法二:

用内置函数:
 

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        String doubleS = s + s;
        if(doubleS.substring(1,doubleS.length() - 1).contains(s)){
            return true;
        }
        return false;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值