[JAVA]窮舉法(暴力法) Exhaustive Algorithm

關於字符串的匹配問題;主字符串1 —> str1 = "xxxxI write themxxxxxxxx I write them here shows what I have been learning." ;
字符串2 —> str2= "I write them here shows what I have been learning.";
若字符串1包含字符串2,則返回開始出現的位置;否則返回-1;

參考來源:https://blog.csdn.net/MrTumnus/article/details/121679134

package utitled;

public class ExhaustiveAlgorithmDemo {

    /**
     * 窮舉法(暴力法)
     * 若使用暴力匹配的方式,需要依次尋找是否存在;假如父級字符串str1 有個指針i ; 子級字符串str2 有個指著j;
     * (1)當str1.charAt( i ) == str2.charAt( j ) ;i+=1;j+=1,兩個字符串的指針均向後移動;
     * (2)若當前不相等時,則需要將子級字符串str2的指針j 歸零; 然後是字符串str1的指針需要回溯:i=i-(j-1)
     */
    public static void main(String[] args) {
        String s1 = "xxxxI write themxxxxxxxx I write them here shows what I have been learning.";
        String s2 = "I write them here shows what I have been learning.";
        int i = exhaustiveAlgorithm(s1, s2);
        System.out.printf("匹配字串從index=%d開始", i);
    }

    private static int exhaustiveAlgorithm(String s1, String s2) {
        char[] chars1 = s1.toCharArray();
        char[] chars2 = s2.toCharArray();
        int i = 0, j = 0;
        while (i < chars1.length && j < chars2.length) {
            if (chars1[i] == chars2[j]) {
                i++;
                j++;
            } else {
                i = i - (j - 1);
                j = 0;
            }
        }
        if (j == chars2.length) {
            return i - chars2.length;
        } else {
            return -1;
        }
    }
}

如有敘述錯誤,還請不吝嗇留言指教,thanks!