package algorithm;
/**
* @author taoke
* @desc KMP算法寻找最小字符串索引
* @email 1504806660@qq.com
* @date 2022/1/24
*/
public class KMP {
public static void main(String[] args) {
String str = "ababc";
int i = kmpSearch(str, "abc", pmt(str));
System.out.println(i);
}
/**
* kmp算法
*
* @param str1 字符串1
* @param str2 字符串2
* @param next pmt数组
* @return 待查找下标
*/
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;
}
/**
* 获取一个字符串的部分匹配值表(PMT)
*
* @param str 字符串
* @return 部分匹配值表
*/
public static int[] pmt(String str) {
int[] next = new int[str.length()];
for (int i = 1, j = 0; i < str.length(); i++) {
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;
}
}
常用的十大算法-KMP算法
最新推荐文章于 2026-01-05 22:36:07 发布
本文介绍了一种高效的字符串搜索算法——KMP算法,并提供了详细的实现步骤。通过实例演示了如何使用KMP算法在主字符串中查找模式字符串的位置,同时介绍了部分匹配表(PMT)的构建方法。
1021

被折叠的 条评论
为什么被折叠?



