简介
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gB8eIMwp-1647485981618)(C:\Users\许正\AppData\Roaming\Typora\typora-user-images\image-20220317095526250.png)]](https://i-blog.csdnimg.cn/blog_migrate/aa28950be18546680e13d474cf7e89f6.png)
暴力求解–字符串匹配问题
package com.xz.kmp;
public class ViolenceMatch {
public static void main(String[] args) {
String str1 = "ABCDEEBF DASFJAISDOFIKCKDCO";
String str2 = "DAS";
System.out.println(violenceMatch(str1, str2));
}
public static int violenceMatch(String str1, String str2) {
char[] s1 = str1.toCharArray();
char[] s2 = str2.toCharArray();
int s1Len = s1.length;
int s2Len = s2.length;
int i = 0;
int j = 0;
while (i < s1Len && j < s2Len) {
if (s1[i] == s2[j]) {
i++;
j++;
} else {
i = i - (j - 1);
j = 0;
}
}
if (j == s2Len) {
return i - j;
} else {
return -1;
}
}
}
KMP算法求解
package com.xz.kmp;
import java.util.Arrays;
public class KMPAlgorithm {
public static void main(String[] args) {
String str1 = "BBC ABCDAB ABCDABCDABDE";
String str2 = "ABCDABD";
int[] next = kmpNext("ABCDABD");
System.out.println("next=" + Arrays.toString(next));
int index = kmpSearch(str1, str2, next);
System.out.println("index=" + index);
}
public static int kmpSearch(String str1, String str2, int[] next) {
for (int i = 0, j = 0; i < str1.length(); i++) {
while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
j = next[j - 1];
}
if (str1.charAt(i) == str2.charAt(j)) {
j++;
}
if (j == str2.length()) {
return i - j + 1;
}
}
return -1;
}
public static int[] kmpNext(String dest) {
int[] next = new int[dest.length()];
next[0] = 0;
for (int i = 1, j = 0; i < dest.length(); i++) {
while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
j = next[j - 1];
}
if (dest.charAt(i) == dest.charAt(j)) {
j++;
}
next[i] = j;
}
return next;
}
}