参考:图解KMP算法 https://leetcode-cn.com/problems/shortest-palindrome/solution/tu-jie-kmpsuan-fa-by-yangbingjie/ (这个解释里 i表示前缀初始位置,j表示后缀初始位置)
1 import java.util.Arrays; 2 3 public class Test { 4 5 /** 6 * @param str 文本串 7 * @param dest 模式串 8 * @param next 匹配核心数组 9 * @return 10 */ 11 public static int kmp(String str, String dest,int[] next) { 12 for(int i = 0, j = 0; i < str.length(); i++){ 13 if (j > 0 && str.charAt(i) != dest.charAt(j)) { 14 j = next[j - 1]; 15 } 16 if (str.charAt(i) == dest.charAt(j)) { 17 j++; 18 } 19 if (j == dest.length()) { 20 return i-j+1; 21 } 22 } 23 return 0; 24 } 25
26 public static int[] kmpnext(String dest) { 27 int[] next = new int[dest.length()]; 28 next[0] = 0; 29 for(int i = 1,j = 0; i < dest.length(); i++) { 30 if (j > 0 && dest.charAt(j) != dest.charAt(i)) { 31 j = next[j - 1]; 32 } 33 if (dest.charAt(i) == dest.charAt(j)) { 34 j++; 35 } 36 next[i] = j; 37 } 38 return next; 39 } 40 50 }
原文:https://www.cnblogs.com/Melo-ccyfy/p/14507914.html