KMP算法使用JAVA语言实现。
package BFKMPBM; public class BFMatching { public static void main(String[] args) { long startTime; long endTime; long durationTime; startTime = System.nanoTime(); KMP(); endTime = System.nanoTime(); durationTime = endTime - startTime; System.out.println(durationTime); } //KMP算法 public static void KMP() { String KMP_S = "BBC ABCDAB ABCDABCDABDE"; String KMP_T = "ABCDABD"; int KMPSLength = KMP_S.length(); //主串长度 int KMPTLength = KMP_T.length(); //子串长度 for (int i = 0; i < KMPSLength;) { for (int j = 0; j < KMPTLength;) { if (KMP_S.charAt(i) != KMP_T.charAt(j)) { //49~55行主要是对模式串的观察编写 if (j > 0 && j < 4) { i = i - 1; j = 0; } else if (j == 6) { i = i - 3; j = 0; } i++; } else if (KMP_S.charAt(i) == KMP_T.charAt(j)) { System.out.println(KMP_S.charAt(i) + "==" + KMP_T.charAt(j)); if (j == 6) { System.out.println("匹配成功!"); return; } i++; j++; } } } } } ????
KMP算法重点在于对模式串的观察!建议在第28行设置断点,单步调试,观看代码执行顺序。在自己动手写算法代码的时候才发现调试功能是如此的重要。
原文地址:http://blog.csdn.net/yxdayd/article/details/45534573