暴力匹配算法的实现,没有匹配就后移一位(粗暴,简单容易理解):
package com.demo.kmp;
public class ViolenceMatch {
public static void main(String[] args) {
String str1 ="abcdefgf";
String str2 = "fgf";
System.out.println(violencematch(str1, str2));
}
public static int violencematch(String str1,String str2){
// 方法一
/* for (int i = 0,j=0; i <str1.length() ; i++) {
if (str1.charAt(i)==str2.charAt(j)){
j++;
}
if (j==str2.length()){
return i-j+1;
}
}
return -1;
*/
// 方法二
char[] s1 = str1.toCharArray();//字符串上转换为字符数组
char[] s2 = str2.toCharArray();
int s1Len = s1.length;
int s2Len = s2.length;
int i=0,j=0;//指向s1,s2的索引
while(i<s1Len&&j<s2Len){
if (s1[i]==s2[j]){
i++;
j++;
}else {//没有匹配成功
i=i-(j-1);
}
if (j==s2Len){
return i-j;
}
}
return -1;
}
}