实现 strStr()(28-kmp算法)

class Solution {
    
    
    public int strStr(String haystack, String needle) {
    
    
            int n1 = haystack.length();
            int n2 = needle.length();
            int result=0;
            if(n2 <=0)
                return result;
            for(int i =0;i<n1;i++){
    
    
                if(haystack.charAt(i) == needle.charAt(0)){
    
    
                    result = i;
                    if(i+n2 > n1)
                        return -1;
                    if(haystack.substring(i,i+n2).equals(needle)){
    
    
                        return result;
                    }
                }
            }
            return -1;
    }
}

KMP

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

おすすめ

転載: blog.csdn.net/qq_51985653/article/details/120985738