【问题标题】:Longest repeating and non-overlapping substring in a huge string大字符串中最长的重复且不重叠的子字符串
【发布时间】:2020-04-27 11:04:58
【问题描述】:

我使用这个程序来查找字符串中最长的重复子字符串。我在这个链接上找到了它(https://www.geeksforgeeks.org/longest-repeating-and-non-overlapping-substring/)。如果我的输入是一个较小的字符串,这个程序就可以完美运行。

    static String longestRepeatedSubstring(String str) { 
        int n = str.length(); 
        int LCSRe[][] = new int[n + 1][n + 1]; 

        String res = ""; // To store result  
        int res_length = 0; // To store length of result  

        int i, index = 0; 
        for (i = 1; i <= n; i++) { 
            for (int j = i + 1; j <= n; j++) { 
                if (str.charAt(i - 1) == str.charAt(j - 1) 
                        && LCSRe[i - 1][j - 1] < (j - i)) { 
                    LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1; 

                    if (LCSRe[i][j] > res_length) { 
                        res_length = LCSRe[i][j]; 
                        index = Math.max(i, index); 
                    } 
                } else { 
                    LCSRe[i][j] = 0; 
                } 
            } 
        } 

        if (res_length > 0) { 
            for (i = index - res_length + 1; i <= index; i++) { 
                res += str.charAt(i - 1); 
            } 
        } 

        return res; 
    } 

    public static void main(String[] args) { 
        String str = "abracadabra"; 
        System.out.println(longestRepeatedSubstring(str)); 
    } 

但是我有一个包含 14553776 个字符的字符串,当我运行程序时,我总是得到java.lang.OutOfMemoryError: Java heap space。我试过增加堆大小和虚拟内存。

我想知道有没有办法解决这个问题。可能需要改进程序或任何其他解决方案?

感谢您的帮助

【问题讨论】:

    标签: java search substring out-of-memory heap-size


    【解决方案1】:

    那是因为这段代码将结果存储为新字符串:

    String res = ""; // To store result
    

    所以这里:

    for (i = index - res_length + 1; i <= index; i++) { 
                res += str.charAt(i - 1); 
            } 
    

    存在内存泄漏。 您需要存储结果字符串的索引。

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2014-11-01
      相关资源
      最近更新 更多