public static int bf(String target, String pattern) {
int tLen = target.length();
int pLen = pattern.length();
if (tLen < pLen) {
return -1;
}
for (int i = 0; i < tLen - pLen + 1; ++i) {
int j = 0;
for (; j < pLen; ++j) {
if (target.charAt(i + j) != pattern.charAt(j)) {
break;
}
}
if (j == pLen) {
return i;
}
}
return -1;
}
public static List<Integer> bf2(String target, String pattern) {
int tLen = target.length();
int pLen = pattern.length();
List<Integer> list = new ArrayList<>();
if (tLen < pLen) {
return list;
}
for (int i = 0; i < tLen - pLen + 1; ++i) {
int j = 0;
for (; j < pLen; ++j) {
if (target.charAt(i + j) != pattern.charAt(j)) {
break;
}
}
if (j == pLen) {
list.add(i);
}
}
return list;
}
public static void main(String[] args) {
String target = "abcabcab";
String pattern = "ab";
int len = pattern.length();
int index = bf(target, pattern);
if (index < 0) {
System.out.println("未找到匹配");
} else {
System.out.println(target.substring(index, index + len));
}
List<Integer> list = bf2(target, pattern);
if (list.isEmpty()) {
System.out.println("未找到匹配");
} else {
System.out.println(list);
}
}