package a8;
public class ViolenceMatchDemo {
public static void main(String[] args) {
String s1 = "asdjlfkjsalkfjklas";
String s2 = "djlfkjc";
int i = matchStr(s1, s2);
System.out.println("i = " + i);
}
private static int matchStr(String s1, String s2) {
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
int l1 = c1.length;
int l2 = c2.length;
int i = 0;//s1 的索引
int j = 0;//s2的索引
while (i < l1 && j < l2) {
//以上的判断就是为了保证检索的时候不越界
if (c1[i] == c2[j]) {
i++;
j++;
} else {
i = i - j +1;
j = 0;
}
}
if (j == l2) {//判断结束的条件。如果j不是0
return i - j;
} else {
return -1;
}
}
}
算法4-0 字符串的暴力匹配
最新推荐文章于 2022-12-08 20:38:30 发布