首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >最长公共子串:递归解决方案?

最长公共子串:递归解决方案?
EN

Stack Overflow用户
提问于 2014-07-03 14:46:41
回答 11查看 11.6K关注 0票数 9

常见的子串算法:

代码语言:javascript
复制
LCS(x,y) = 1+ LCS(x[0...xi-1],y[0...yj-1] if x[xi]==y[yj]
           else 0

现在,动态编程解决方案已经很好地理解了。然而,我找不出递归的解决方案。如果有多个子字符串,那么上面的算法似乎失败了。

例如:

代码语言:javascript
复制
x = "LABFQDB" and y = "LABDB"

应用上述算法

代码语言:javascript
复制
1+ (x=  "LABFQD" and y = "LABD")
1+ (x=  "LABFQ" and y = "LAB")
return 0 since 'Q'!='B'

返回值应该是2,而我应该是3?

有人能指定一个递归解决方案吗?

EN

回答 11

Stack Overflow用户

发布于 2019-11-02 12:06:52

尽量避免混淆,你问的是longest common substring,而不是longest common subsequence,它们很相似,但却是have differences

代码语言:javascript
复制
The recursive method for finding longest common substring is:
Given A and B as two strings, let m as the last index for A, n as the last index for B.

    if A[m] == B[n] increase the result by 1.
    if A[m] != B[n] :
      compare with A[m -1] and B[n] or
      compare with A[m] and B[n -1] 
    with result reset to 0.

下面是没有应用memoization的代码,以便更好地说明算法。

代码语言:javascript
复制
   public int lcs(int[] A, int[] B, int m, int n, int res) {
        if (m == -1 || n == -1) {
            return res;
        }
        if (A[m] == B[n]) {
            res = lcs(A, B, m - 1, n - 1, res + 1);
        }
        return max(res, max(lcs(A, B, m, n - 1, 0), lcs(A, B, m - 1, n, 0)));
    }

    public int longestCommonSubString(int[] A, int[] B) {
        return lcs(A, B, A.length - 1, B.length - 1, 0);
    }
票数 11
EN

Stack Overflow用户

发布于 2018-08-02 21:12:36

打包algo.dynamic;

公共类LongestCommonSubstring {

代码语言:javascript
复制
public static void main(String[] args) {
    String a = "LABFQDB";
    String b = "LABDB";
    int maxLcs = lcs(a.toCharArray(), b.toCharArray(), a.length(), b.length(), 0);
    System.out.println(maxLcs);
}

private static int lcs(char[] a, char[] b, int i, int j, int count) {
    if (i == 0 || j == 0)
        return count;
    if (a[i - 1] == b[j - 1]) {
        count = lcs(a, b, i - 1, j - 1, count + 1);
    }
    count = Math.max(count, Math.max(lcs(a, b, i, j - 1, 0), lcs(a, b, i - 1, j, 0)));
    return count;
}

}

票数 1
EN

Stack Overflow用户

发布于 2020-06-28 23:36:00

下面是最长公共子串的递归代码:

代码语言:javascript
复制
int LCS(string str1, string str2, int n, int m, int count)
{
    if (n==0 || m==0)
        return count;
    if (str1[n-1] == str2[m-1])
        return LCS(str1, str2, n-1, m-1, count+1);
    return max(count, max(LCS(str1, str2, n-1, m, 0), LCS(str1, str2, n, m-1, 0)));
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24546740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档