JAVA实现KMP

class KMP {
    //计算next数组
    private static int[] getNextArray(String str) {
        if (str.length() == 1) {
            return new int[]{0};
        }
        int[] res = new int[str.length()];
        res[0] = -1;
        res[1] = 0;
        int curJump = 0;
        int i = 2;
        while (i < str.length()) {
            if (str.charAt(i - 1) == str.charAt(curJump)) {
                res[i++] = ++curJump;
            } else if (curJump > 0) {
                curJump = res[curJump];
            } else {
                i++;
            }
        }
        return res;
    }

    //时间、空间复杂度都是O(n)
    private static int myIndexOf(String str1, String str2) {
        if (str1 == null || str2 == null || str2.length() > str1.length()) {
            return -1;
        }
        if (str1.equals(str2)) {
            return 0;
        }
        //计算next数组,这样就不用每次都i++,可以起到剪枝的效果
        int[] nextArray = getNextArray(str2);
        int i = 0;
        int j = 0;
        while (i < str1.length() && j < str2.length()) {
            if (str1.charAt(i) == str2.charAt(j)) {
                i++;
                j++;
            } else if (j > 0) {
                j = nextArray[j];
            } else {
                i++;
            }
        }
        return j == str2.length() ? i - j : -1;
    }

    public static void main(String[] args) {
        String s1 = "abcca";
        String s2 = "ca";
        int res1 = myIndexOf(s1, s2);
        int res2 = s1.indexOf(s2);
        System.out.println(res1 == res2);
    }
}

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