【问题标题】:How can I get Space complexity O(n) while looking for the longest common substring [DP]?如何在寻找最长公共子串 [DP] 时获得空间复杂度 O(n)?
【发布时间】:2018-11-24 14:29:58
【问题描述】:

¡你好!

在使用动态编程之后,我正在尝试以良好的时间和空间复杂度找到两个字符串之间的最长公共子字符串。我可以找到具有 O(n^2) 时间和空间复杂度的解决方案:

public static String LCS(String s1, String s2){
    int maxlen = 0;            // stores the max length of LCS      
    int m = s1.length();
    int n = s2.length();
    int endingIndex = m;  // stores the ending index of LCS in X

    // lookup[i][j] stores the length of LCS of substring
    // X[0..i-1], Y[0..j-1]
    int[][] lookup = new int[m + 1][n + 1];

    // fill the lookup table in bottom-up manner
    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            // if current character of X and Y matches
            if (s1.charAt(i - 1) == s2.charAt(j - 1))
            {
                lookup[i][j] = lookup[i - 1][j - 1] + 1;

                // update the maximum length and ending index
                if (lookup[i][j] > maxlen)
                {
                    maxlen = lookup[i][j];
                    endingIndex = i;
                }
            }
        }
    }

    // return Longest common substring having length maxlen
    return s1.substring(endingIndex - maxlen, endingIndex);

}

我的问题是:如何获得更好的空间复杂度?

提前致谢!

【问题讨论】:

  • 你怎么知道有可能得到 O(n) 时间?你的来源是什么?回答这个问题,你就已经回答了一半了。
  • 不,不是。我在问常见的子串空间复杂度,而这个问题是在问常见的子序列时间复杂度

标签: java dynamic-programming space-complexity


【解决方案1】:

使用动态规划求两个字符串的 LCS 的最佳时间复杂度是 O(n^2)。我试图为这个问题找到另一种算法,因为它是我的大学项目之一。但我能找到的最好的东西是复杂度为 O(n^3) 的算法。这个问题的主要解决方案使用“递归关系”,它使用更少的空间但更多的过程。但就像“斐波那契数列”一样,计算机科学家使用动态编程来降低时间复杂度。 递归关系代码:

void calculateLCS(string &lcs , char frstInp[] , char secInp[] , int lengthFrstInp ,  int lengthSecInp) {

if (lengthFrstInp == -1 || lengthSecInp == -1)
    return;

if (frstInp[lengthFrstInp] == secInp[lengthSecInp]) {
    lcs += frstInp[lengthFrstInp];
    lengthFrstInp--;
    lengthSecInp--;
    calculateLCS(lcs, frstInp, secInp, lengthFrstInp, lengthSecInp);

}


else {

    string lcs1 ="";
    string lcs2 ="";    
    lcs1 = lcs;
    lcs2 = lcs;
    calculateLCS(lcs1, frstInp, secInp, lengthFrstInp, lengthSecInp - 1);
    calculateLCS(lcs2, frstInp, secInp, lengthFrstInp - 1, lengthSecInp);

    if (lcs1.size() >= lcs2.size())
        lcs = lcs1;
    else
        lcs = lcs2;

}

【讨论】:

  • 感谢您的帮助!但是,我不能为了空间复杂度而牺牲时间复杂度^^(我也应该使用 DP!)
猜你喜欢
  • 2021-05-21
  • 2015-05-25
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多