代码随想录算法训练营第9天 | 28.找出字符串中第一个匹配项的下标、459.重复的子字符串

题目链接:28. 找出字符串中第一个匹配项的下标 - 力扣(LeetCode)

class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack == null || haystack.length() == 0 || needle == null || needle.length() == 0){
            return -1;
        }
        int[] next = nextArr(needle);
        int j = 0;
        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 int[] nextArr(String needle){
        if(needle.length() == 1){
            int[] nextArr = new int[]{0};
            return nextArr;
        }else{
            int[] next = new int[needle.length()];
            next[0] = 0;
            int j = 0;
            for(int i = 1; i < needle.length(); i ++){
                while(j > 0 && needle.charAt(i) != needle.charAt(j)){
                    j = next[j - 1];
                }
                if(needle.charAt(i) == needle.charAt(j)){
                    j ++;
                }
                next[i] = j;
            }
            return next;
        }
        
    }
}

重点在于求next数组

题目链接:459. 重复的子字符串 - 力扣(LeetCode)

class Solution {
    public boolean repeatedSubstringPattern(String s) {
        if(s.length() == 1){
            return false;
        }
        int[] next = new int[s.length()];
        int j = 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;
        }
        if(next[s.length() - 1] == 0){
            return false;
        }
        int n = s.length() % (s.length() - next[s.length() - 1]);
        if(n == 0){
            return true;
        }
        return false;
    }
}

这里是求next数组的解法,另一种解法是将两个字符串拼接,掐头去尾,再在里面找是否有原始字符串

你可能感兴趣的:(算法,leetcode,java)