https://blog.csdn.net/qq1137623160/article/details/102589408
###暴力匹配

//一般情况下暴力匹配
private static int violenceMatch(String str1, String str2) {
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;

        int i = 0; // i索引指向s1
        int j = 0; // j索引指向s2

        while (i < s1Len && j < s2Len) {// 保证匹配时,不越界
            if (s1[i] == s2[j]) {//匹配 ok
                i++;
                j++;
            } else { //没有匹配成功
                //如果失配(即 str1[i]! = str2[j]),令 i = i - (j - 1),j = 0。
                i = i - (j - 1);
                j = 0;
            }
        }

        //判断是否匹配成功
        if (j == s2Len) {
            return i - j;
        } else {
            return -1;
        }
    }
}

KMP算法

public static int strStr(String haystack, String needle) {

        int needleLen = needle.length();
        if(needleLen == 0) {
            return 0;
        }

        int[] next = new int[needleLen];
        next[0] = -1;
        int j = -1;
        int i = 0;
        /*getNext*/
        while (i < needleLen - 1) {
            if (j == -1 || needle.charAt(j) == needle.charAt(i)) {        
                j++;
                i++;
                next[i] = j;
            } else {
                j = next[j];
            }
        }
        i = 0;
        j = 0;
        /*matching*/
        while (i < haystack.length() && j < needle.length()) {
            if (j == -1 || haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            } else {
                j = next[j];
            }
        }
        if (j == needle.length()) {
            return i - j;
        }
        return -1;
    }