一个视频让你彻底学懂KMP算法_哔哩哔哩_bilibili
KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。
public class KMP {// 计算部分匹配表 (LPS)private static int[] computeLPSArray(String pattern) {int[] lps = new int[pattern.length()];int length = 0; // 长度为当前最长前缀后缀int i = 1;while (i < pattern.length()) {if (pattern.charAt(i) == pattern.charAt(length)) {length++;lps[i] = length;i++;} else {if (length != 0) {length = lps[length - 1]; // 回溯} else {lps[i] = 0;i++;}}}return lps;}// KMP 查找算法public static boolean kmpSearch(String text, String pattern) {int[] lps = computeLPSArray(pattern);int i = 0; // 文本的索引int j = 0; // 模式串的索引while (i < text.length()) {if (pattern.charAt(j) == text.charAt(i)) {i++;j++;}if (j == pattern.length()) {return true; // 找到匹配} else if (i < text.length() && pattern.charAt(j) != text.charAt(i)) {if (j != 0) {j = lps[j - 1]; // 根据 LPS 表回溯} else {i++;}}}return false; // 未找到匹配}public static void main(String[] args) {String text = "aaaaaaac";String pattern = "aaaac";boolean found = kmpSearch(text, pattern);if (found) {System.out.println("子串 \"" + pattern + "\" 在主串中出现过。");} else {System.out.println("子串 \"" + pattern + "\" 在主串中未出现。");}}
}
相关:
https://blog.csdn.net/qq_43197840/article/details/140680621?spm=1001.2014.3001.5501
https://blog.csdn.net/qq_43197840/article/details/140679425?spm=1001.2014.3001.5501