BF algorithm (Java)

Algorithm idea:

From the first character of the first character string beginning with master pattern string comparison start
the next if the same, the primary string and string comparison are beginning to
, if not identical
pattern string is returned to the original position, the master returns to the main string string subtracting the model train position position position plus one
and so on, until it finds a string pattern matching in the main stream.

package String;

public class Brute_Force {
    public static void main(String[] args) {
        String main="ahsdghsfdhfksjdjjh";
        String sub="hsf";
        int i = indexOf(main, sub);
        System.out.println(i);
    }
    public static int indexOf(String mainStr,String pattern){
        if(mainStr != null && pattern != null && pattern.length() > 0 && mainStr.length() > pattern.length()){
            int i=0,j=0;//i,j为目标串和模式串的当前字符小标
            //当目标串与模式串的第一个字符匹配时,i++,j++
            while (i<mainStr.length() && j<pattern.length()){
                if (mainStr.charAt(i)==pattern.charAt(j)){
                    i++;
                    j++;
                }else{//否则i返回到开始位置的后一位,j下标为0
                    i=i-j+1;
                    j=0;
                }
            }
            if (j==pattern.length()){//匹配成功
                return i-j;
            }
        }
        return -1;
    }
}
Released three original articles · won praise 3 · views 79

Guess you like

Origin blog.csdn.net/weixin_46535360/article/details/104825950