Java实现KMP算法

转自:http://blog.csdn.net/tkd03072010/article/details/6824326

——————————————————————————————————

  1. package arithmetic;  
  2.   
  3. /** 
  4.  * Java实现KMP算法 
  5.  *  
  6.  * 思想:每当一趟匹配过程中出现字符比较不等,不需要回溯i指针,  
  7.  * 而是利用已经得到的“部分匹配”的结果将模式向右“滑动”尽可能远  
  8.  * 的一段距离后,继续进行比较。 
  9.  *  
  10.  * 时间复杂度O(n+m) 
  11.  *  
  12.  * @author xqh 
  13.  *  
  14.  */  
  15. public class KMPTest {  
  16.     public static void main(String[] args) {  
  17.         String s = "abbabbbbcab"; // 主串   
  18.         String t = "bbcab"; // 模式串   
  19.         char[] ss = s.toCharArray();  
  20.         char[] tt = t.toCharArray();  
  21.         System.out.println(KMP_Index(ss, tt)); // KMP匹配字符串   
  22.     }  
  23.   
  24.     /** 
  25.      * 获得字符串的next函数值 
  26.      *  
  27.      * @param t 
  28.      *            字符串 
  29.      * @return next函数值 
  30.      */  
  31.     public static int[] next(char[] t) {  
  32.         int[] next = new int[t.length];  
  33.         next[0] = -1;  
  34.         int i = 0;  
  35.         int j = -1;  
  36.         while (i < t.length - 1) {  
  37.             if (j == -1 || t[i] == t[j]) {  
  38.                 i++;  
  39.                 j++;  
  40.                 if (t[i] != t[j]) {  
  41.                     next[i] = j;  
  42.                 } else {  
  43.                     next[i] = next[j];  
  44.                 }  
  45.             } else {  
  46.                 j = next[j];  
  47.             }  
  48.         }  
  49.         return next;  
  50.     }  
  51.   
  52.     /** 
  53.      * KMP匹配字符串 
  54.      *  
  55.      * @param s 
  56.      *            主串 
  57.      * @param t 
  58.      *            模式串 
  59.      * @return 若匹配成功,返回下标,否则返回-1 
  60.      */  
  61.     public static int KMP_Index(char[] s, char[] t) {  
  62.         int[] next = next(t);  
  63.         int i = 0;  
  64.         int j = 0;  
  65.         while (i <= s.length - 1 && j <= t.length - 1) {  
  66.             if (j == -1 || s[i] == t[j]) {  
  67.                 i++;  
  68.                 j++;  
  69.             } else {  
  70.                 j = next[j];  
  71.             }  
  72.         }  
  73.         if (j < t.length) {  
  74.             return -1;  
  75.         } else  
  76.             return i - t.length; // 返回模式串在主串中的头下标   
  77.     }  
  78. }  

posted on 2014-10-06 14:16  凯撒帝  阅读(835)  评论(0编辑  收藏  举报

导航