编辑代码

public class zuoye {
    public static void main(String[] args) {
        String parent="hello word";
        String sub="h";
        bruteForce(parent,sub);
    }

    public static void bruteForce(String parent,String sub){
        //成功匹配的位置
        int index = -1;
        //主串的长度
        int pLen = parent.length();
        //子串的长度
        int sLen = sub.length();

        if (pLen<sLen){
            System.out.println("Error.The main string is greater than the sub string length.");
            return;
        }
        int i = 0;
        int j = 0;
        while (i<pLen&&j<sLen){
            // 判断对应位置的字符是否相等
            if (parent.charAt(i)==sub.charAt(j)){
                //若相等.主串子串继续比较
                i++;
                j++;
            }else{
                //主串回溯到上一次开始匹配的下一个字符
                i = i- j+1;
                j = 0;
            }
        }
        //匹配成功
        if (j >= sLen) {
            index = i - j;
            System.out.println("匹配成功,索引:" + index);
        } else {// 匹配失败
            System.out.println("匹配失败");
        }
    }
}