Day8 | 28实现strStr()&459重复的子字符串

56 阅读1分钟

实现strStr() LeetCode 28

题目链接:[LeetCode 28 - 简单]

思路

看到了题意想到用KMP来解决。

KMP:

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

总结

KMP的前缀表有减一和不减一两种方法,以上为减一的方法。主要用来字符串的匹配。

重复的子字符串 LeetCode 459

题目链接:[LeetCode 459 - 简单]

思路

使用KMP来解决,如#28。

KMP:

java
class Solution {
    public boolean repeatedSubstringPattern(String s) {
        if(s.equals(""))return true;

        int len = s.length();
        int[] next = new int[len+1];
        s = " "+s;
        for(int i=2,j=0;i<=len;i++){
            while(j>0 && s.charAt(i)!=s.charAt(j+1)){
                j = next[j];
            }
            if(s.charAt(i)==s.charAt(j+1)){
                j++;
            }
            next[i]=j;
        }
        if(next[len]>0 && len%(len-next[len])==0)
            return true;
        return false;
    }
}