Brute-Force模式匹配演算法兩種實現方式
阿新 • • 發佈:2018-10-31
1.
public static int indexOf(String mainStr,String subString,int start) { if((mainStr.length()<subString.length()) || mainStr==null || subString==null ) { return -1; } for (int i = start; i <= mainStr.length()-subString.length(); i++) { int j; for (j= i; j < i+subString.length(); j++) { if(mainStr.charAt(j)!=subString.charAt(j-i)) { break; } } if(j==i+subString.length()) { return i; } } return -1; }
2.
public static int indexOf(String mainString,String subString,int start) { int i = start; int j = 0;; if(mainString==null || subString==null || (mainString.length()<subString.length())) { return -1; } while(i<mainString.length() && j<subString.length()) { if(mainString.charAt(i)==subString.charAt(j)) { i++; j++; }else { i = i-j+1; j = 0; } if((i+subString.length())>mainString.length()) { return -1; } } if(j==subString.length()) { return i-j; } return -1; }