首页 > 编程语言 > 详细

KMP算法-JAVA代码

时间:2021-03-09 22:18:54      阅读:31      评论:0      收藏:0      [点我收藏+]

参考:图解KMP算法 https://leetcode-cn.com/problems/shortest-palindrome/solution/tu-jie-kmpsuan-fa-by-yangbingjie/ (这个解释里 i表示前缀初始位置,j表示后缀初始位置)

 1 import java.util.Arrays;
 2  
 3 public class Test {
 4  
 5     /**
 6      * @param str 文本串
 7      * @param dest 模式串
 8      * @param next 匹配核心数组
 9      * @return
10      */
11     public static int kmp(String str, String dest,int[] next) {
12         for(int i = 0, j = 0; i < str.length(); i++){
13             if (j > 0 && str.charAt(i) != dest.charAt(j)) {
14                 j = next[j - 1];
15             }
16             if (str.charAt(i) == dest.charAt(j)) {
17                 j++;
18             }
19             if (j == dest.length()) {
20                 return i-j+1;
21             }
22         }
23         return 0;
24     }
25  
     26 public static int[] kmpnext(String dest) { 27 int[] next = new int[dest.length()]; 28 next[0] = 0; 29 for(int i = 1,j = 0; i < dest.length(); i++) { 30 if (j > 0 && dest.charAt(j) != dest.charAt(i)) { 31 j = next[j - 1]; 32 } 33 if (dest.charAt(i) == dest.charAt(j)) { 34 j++; 35 } 36 next[i] = j; 37 } 38 return next; 39 } 40 50 }

 

KMP算法-JAVA代码

原文:https://www.cnblogs.com/Melo-ccyfy/p/14507914.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!