【转】KMP算法

参考
https://blog.51cto.com/acevi/2104820
https://www.jianshu.com/p/e2bd1ee482c3
https://blog.csdn.net/v_july_v/article/details/7041827

leetcode 28 Implement strStr()

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:

Input: haystack = “aaaaa”, needle = “bba”
Output: -1

code

class Solution {
    public int strStr(String haystack, String needle) {
        if (needle.isEmpty())
            return 0;
        
        if (haystack == null || needle == null)
            return -1;
        
        //generate next array, need O(n) time
        int i = -1, j = 0, m = haystack.length(), n = needle.length();
        int[] next = new int[n];
        if (next.length > 0){
            next[0] = -1;
            while (j < n - 1) {
                if (i == -1 || needle.charAt(i) == needle.charAt(j))
                    next[++j] = ++i;
                else 
                    i = next[i];
            }
        }
        
        //check through the haystack using next, need O(m) time
        i = 0; j = 0;
        while (i < m && j < n) {
            if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            }else 
                j = next[j];
        }
        if (j == n)
            return i - j;
        return -1;   
    }
}

你可能感兴趣的:(数据结构和算法)