• Java实现KMP算法



    1. package arithmetic;  
    2.   
    3. /** 
    4.  * Java实现KMP算法 
    5.  *  
    6.  * 思想:每当一趟匹配过程中出现字符比较不等,不需要回溯i指针,  
    7.  * 而是利用已经得到的“部分匹配”的结果将模式向右“滑动”尽可能远  
    8.  * 的一段距离后,继续进行比较。 
    9.  *  
    10.  * 时间复杂度O(n+m) 
    11.  *  
    12.  * @author 青梅
    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.      * KMP匹配字符串 
    26.      *  
    27.      * @param s 
    28.      *            主串 
    29.      * @param t 
    30.      *            模式串 
    31.      * @return 若匹配成功,返回下标,否则返回-1 
    32.      */  
    33.     public static int KMP_Index(char[] s, char[] t) {  
    34.         int[] next = next(t);  
    35.         int i = 0;  
    36.         int j = 0;  
    37.         while (i <= s.length - 1 && j <= t.length - 1) {  
    38.             if (j == -1 || s[i] == t[j]) {  
    39.                 i++;  
    40.                 j++;  
    41.             } else {  
    42.                 j = next[j];  
    43.             }  
    44.         }  
    45.         if (j < t.length) {  
    46.             return -1;  
    47.         } else  
    48.             return i - t.length; // 返回模式串在主串中的头下标  
    49.     }  
    50.  
    51.   
    52.     /** 
    53.      * 获得字符串的next函数值 
    54.      *  
    55.      * @param t 
    56.      *            字符串 
    57.      * @return next函数值 
    58.      */  
    59.     public static int[] next(char[] t) {  
    60.         int[] next = new int[t.length];  
    61.         next[0] = -1;  
    62.         int i = 0;  
    63.         int j = -1;  
    64.         while (i < t.length - 1) {  
    65.             if (j == -1 || t[i] == t[j]) {  
    66.                 i++;  
    67.                 j++;  
    68.                 if (t[i] != t[j]) {  
    69.                     next[i] = j;  
    70.                 } else {  
    71.                     next[i] = next[j];  
    72.                 }  
    73.             } else {  
    74.                 j = next[j];  
    75.             }  
    76.         }  
    77.         return next;  
    78.     }  
    79.   
    80.   
    81. }  
     
  • 相关阅读:
    Linux
    C/C++ 引入头文件时 #include<***.h> 与 #include"***.h" 区别
    2018.01.10
    java 选择结构if
    引用数据类型 Scanner Random
    java 运算符
    java变量和数据类型
    Java se基础
    数据库设计
    MySQL 其他基础知识
  • 原文地址:https://www.cnblogs.com/qingmei/p/4120436.html
Copyright © 2020-2023  润新知