Java實現KMP算法

package arithmetic; /** * Java實現KMP算法 * * 思想:每當一趟匹配過程中出現字符比較不等,不需要回溯i指針, * 而是利用已經得到的“部分匹配”的結果將模式向右“滑動”儘可能遠 * 的一段距離後,繼續進行比較。 * * 時間複雜度O(n+m) * * @author xqh * */ public class KMPTest { public static void main(String[] args) { String s = "abbabbbbcab"; // 主串 String t = "bbcab"; // 模式串 char[] ss = s.toCharArray(); char[] tt = t.toCharArray(); System.out.println(KMP_Index(ss, tt)); // KMP匹配字符串 } /** * 獲得字符串的next函數值 * * @param t * 字符串 * @return next函數值 */ public static int[] next(char[] t) { int[] next = new int[t.length]; next[0] = -1; int i = 0; int j = -1; while (i < t.length - 1) { if (j == -1 || t[i] == t[j]) { i++; j++; if (t[i] != t[j]) { next[i] = j; } else { next[i] = next[j]; } } else { j = next[j]; } } return next; } /** * KMP匹配字符串 * * @param s * 主串 * @param t * 模式串 * @return 若匹配成功,返回下標,否則返回-1 */ public static int KMP_Index(char[] s, char[] t) { int[] next = next(t); int i = 0; int j = 0; while (i <= s.length - 1 && j <= t.length - 1) { if (j == -1 || s[i] == t[j]) { i++; j++; } else { j = next[j]; } } if (j < t.length) { return -1; } else return i - t.length; // 返回模式串在主串中的頭下標 } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章