字符串----最长重复子串

题目:求最长重复子串长度(可重复或者可交叉),例如 str = "abcbcbcbc",则最长重复子串为 "bcbcbc",最长重复子串长度为6。

思路:这道题用暴力解法的话不太现实,就算能实现效率也比较低。那这里用到的就是后缀数组+高度数组就能解决问题,这里有个规律:任何的子串都是某一个后缀数组的前缀。而高度数组本身就代表相邻两个后缀之间的最大公共前缀的长度。所以这里求最长重复子串就是求高度数组的最大值。至于后缀数组和高度数组的介绍前面博客有。下面直接给出这道题的解法。

代码:

 1 public class MaxRepeatSubString {
 2 
 3     public static void main(String[] args) {
 4         int res = maxRepeatSubString("123232323");
 5         System.out.println("最长重复子串长度:"+res);
 6     }
 7 
 8     public static int maxRepeatSubString(String src) {
 9         // SuffixArray 在字符串匹配(三)----后缀数组算法这篇博客里
10         SuffixArray.Suff[] sa = SuffixArray.getSa2(src);
11         int[] height = SuffixArray.getHeight(src, sa);
12         int maxHeight = 0;
13         int maxIndex = -1;
14         for (int i = 0; i < height.length; i++) {
15             if (height[i] > maxHeight) {
16                 maxHeight = height[i];
17                 maxIndex = i;
18             }
19         }
20         int index = sa[maxIndex].index;// 转成原始下标
21         System.out.println("最长重复子串:" + src.substring(index, index + maxHeight));
22         return maxHeight;
23     }
24 
25 }

结果:

  

 

posted @ 2019-01-27 17:44  |旧市拾荒|  阅读(878)  评论(0编辑  收藏  举报