LeetCode - 28. 实现strStr()

28. 实现strStr()

import java.util.Objects;

class Solution {

    private int[] getNext(String str) {

        char[] s = str.toCharArray();

        int[] next = new int[s.length];
        next[0] = -1;

        int i = 0;
        int j = -1;

        while (i < s.length - 1) {
            if (j == -1 || s[i] == s[j]) {
                if (s[++ i] == s[++ j]) {
                    next[i] = next[j];
                } else {
                    next[i] = j;
                }
            } else {
                j = next[j];
            }
        }
        return next;
    }

    private int kmp(String str1, String str2) {

        if (Objects.isNull(str1) || Objects.isNull(str2)) {
            return -1;
        }

        if (str2.length() == 0) {
            return 0;
        }

        int i = 0;
        int j = 0;

        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int[] next = getNext(str2);

        while (i < s1.length && j < s2.length) {
            if (j == -1 || s1[i] == s2[j]) {
                ++ i;
                ++ j;
            } else {
                j = next[j];
            }
        }

        if (j == s2.length) {
            return i - j;
        }
        return -1;

    }

    public int strStr(String haystack, String needle) {
        return kmp(haystack, needle);
    }
}


猜你喜欢

转载自blog.51cto.com/tianyiya/2172739