zoukankan      html  css  js  c++  java
  • 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. }  
  • 相关阅读:
    07 MySQL之视图
    05 MySQL之查询、插入、更新与删除
    04 MySQL之函数
    02 MySQL之数据表的基本操作
    03 MySQL之数据类型和运算符
    Django之通用视图
    01 MySQL之数据库基本操作
    Elasticsearch-Head基本使用方法
    PinPoint使用手册(转)
    rest-assured学习资料
  • 原文地址:https://www.cnblogs.com/kaikailele/p/4008192.html
Copyright © 2011-2022 走看看