目录
1. KMP算法介绍
2. KMP算法最佳应用—字符串匹配问题
3. 思路
4. 代码实现
4.1 KMP算法实现
4.2 暴力匹配算法实现
“部分匹配值”就是”前缀”和”后缀”的最长的共有元素的长度。以”ABCDABD”为例,
2. 使用部分匹配表完成KMP
package com.example.datastructureandalgorithm.violence;
import java.util.Arrays;
/**
* @author 浪子傑
* @version 1.0
* @date 2020/6/11
*/
public class KMPDemo {
public static void main(String[] args) {
String str1 = "BBC ABCDAB ABCDABCDABDE";
String str2 = "ABCDABD";
int[] next = kmpNext(str2);
System.out.println(Arrays.toString(next));
System.out.println(kmpSearch(str1, str2, next));
}
/**
* KMP算法查找
*
* @param str1
* @param str2
* @param next
* @return
*/
public static int kmpSearch(String str1, String str2, int[] next) {
for (int i = 0, j = 0; i < str1.length(); i++) {
// TODO 此处暂时无非理解~~
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;
}
/**
* 获取字符串的部分匹配表
*
* @param str
* @return
*/
public static int[] kmpNext(String str) {
// 创建返回的数组
int[] next = new int[str.length()];
next[0] = 0;
// 循环字符串进行比较
for (int i = 1, j = 0; i < str.length(); i++) {
// TODO 此处暂时无非理解~~
while (j > 0 && str.charAt(i) != str.charAt(j)) {
j = next[j - 1];
}
if (str.charAt(i) == str.charAt(j)) {
j++;
}
next[i] = j;
}
return next;
}
}
package com.example.datastructureandalgorithm.violence;
/**
* @author 浪子傑
* @version 1.0
* @date 2020/6/10
*/
public class ViolenceMatch {
public static void main(String[] args) {
String s1 = "我爱你中国亲爱的母亲,亲爱的母亲";
String s2 = "爱的母";
System.out.println(violenceMatch(s1,s2));
}
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;
}
}
}