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("匹配失败");
}
}
}