package sy1;
import java.util.Arrays;
/**
* 尚硅谷
*/
public class KMPAlgorithm {
public static void main(String[] args) {
String str1 = "BBC ABCDAB ABCDABCDABDE";
String str2 = "ABCDABD";
int[] next = kmpNext(str2);
System.out.println("next=" + Arrays.toString(next));
int index = kmpSearch(str1, str2, next);
System.out.println("index=" + index);
}
/**
* @param str1 字符串
* @param str2 子串
* @param next 部分匹配表, 是子串对应的部分匹配表
* @return 如果是-1就是没有匹配到,否则返回第一个匹配的位置
*/
public static int kmpSearch(String str1, String str2, int[] next) {
//遍历str1
for (int i = 0, j = 0; i < str1.length(); i++) {
//处理str1.charAt(i) != str2.charAt(j)
while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
//str1.charAt(i) != str2.charAt(j)重置j的值
j = next[j - 1];
}
//相等j往后走
if (str1.charAt(i) == str2.charAt(j)) {
j++;
}
if (j == str2.length()) {
return i - j + 1;
}
}
return -1;
}
/**
* 获取到一个字符串(子串) 的部分匹配值表
*
* @param dest
* @return 返回部分匹配值表
*/
public static int[] kmpNext(String dest) {
//创建一个数组保存部分匹配值
int[] next = new int[dest.length()];
//长度为1时匹配值为零
next[0] = 0;
//遍历
for (int i = 1, j = 0; i < dest.length(); i++) {
//处理dest.charAt(i) != dest.charAt(j)
while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
//当dest.charAt(i) != dest.charAt(j)重置j的值否则退出
j = next[j - 1];
}
//j往后走
if (dest.charAt(i) == dest.charAt(j)) {
j++;
}
next[i] = j;
}
return next;
}
}
kmp算法
最新推荐文章于 2023-04-09 17:43:52 发布