1. 程式人生 > >java實現KMP算法

java實現KMP算法

java kmp

package net.yk.string; public class KMP { public static void main(String[] args) { String major = "abababcabcabcda"; String mode = "abcd"; int[] next = new KMP().next(mode); System.out.println(new KMP().index_KMP(major, mode, 1, next)); } /** * 獲取字符串的部分匹配值 * @param str * @return */ int[] next(String str) { // 獲取模式串的長度 int len = str.length(); // 創建字符數組用來存儲模式串 char[] mode = new char[len + 1]; int[] next = new int[len + 1]; // 將模式串拷貝到字符數組中,從下標1開始 str.getChars(0, len, mode, 1); int i = 1, j = 0; next[1] = 0; while (i < len) { if (j == 0 || mode[i] == mode[j]) { i++; j++; next[i] = j; } else j = next[j]; } return next; } /** * KMP 算法 * * @param major * @param mode * @param pos * @param next * @return */ int index_KMP(String major, String mode, int pos, int[] next) { int majorL = major.length(); int modeL = mode.length(); //從下標1開始存儲數據 char majorChar[] = new char[majorL + 1]; char modeChar[] = new char[modeL + 1]; major.getChars(0, majorL, majorChar, 1); mode.getChars(0, modeL, modeChar, 1); int i = pos, j = 1; while (i <= majorL && j <= modeL) { if (j == 0 || majorChar[i] == modeChar[j]) { ++i; ++j; } else j = next[j]; } if (j > modeL) { return i - modeL; } else return 0; } }


java實現KMP算法