来自大佬的解说
KMP算法核心是理解前缀表的构造,前缀表是为了在母串中匹配子串不成功后快速移动子串以降低时间复杂度而构造。
这里附上一篇大佬的深入浅出的解释,讲的非常好。
别再暴力匹配字符串了,高效的KMP才是真的香!
作者:奶糖猫
来源:掘金
代码
基本上边抄边写,谁让我是小菜鸡呢。可能会有bug,欢迎和谐讨论。
import java.util.LinkedList;
import java.util.List;
/**
* 参考 https://juejin.cn/post/6844904153123143687
* 讲的很不错
*/
public class KMP {
public static void main(String[] args) {
String s = "abacaababc";
String pattern = "ab";
System.out.println(kmp(s, pattern));
}
public static int[] getPrefixTable(String s) {
if (s == null) throw new NullPointerException();
int i = 1, j =