Longest Common Substring (K3)

原题在这里:

https://leetcode.com/discuss/interview-question/1273766/longest-common-substring

这道题跟https://www.cnblogs.com/feiflytech/p/15841611.html 类似,但是不完全相同:

首选自顶向下写个递归,与1143只有一点点不同。

    private Integer[][] dp;
    private int m, n;

    public int longestCommonSubstring(String text1, String text2) {
        m = text1.length();
        n = text2.length();
        dp = new Integer[m][n];
        return helper(text1, text2, 0, 0);
    }

    private int helper(String text1, String text2, int i, int j) {
        if (i == m || j == n)
            return 0;

        if (dp[i][j] != null)
            return dp[i][j];

        if (text1.charAt(i) == text2.charAt(j)) {
            if(i+1<m && j+1<n && text1.charAt(i+1)==text2.charAt(j+1))
                 return dp[i][j] = 1 + helper(text1, text2, i + 1, j + 1);
            else
                return 1;
        }
        else
            return dp[i][j] = Math.max(
                    helper(text1, text2, i + 1, j),
                    helper(text1, text2, i, j + 1)
            );
    }

然后自底向上写个dp

    public int longestCommonSubstring2(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        int[][] dp = new int[m+1][n+1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if(text1.charAt(i-1)==text2.charAt(j-1)){
                    if(i-2>=0 && j-2>=0 && text1.charAt(i-2)==text2.charAt(j-2)){
                        dp[i][j]=1+dp[i-1][j-1];
                    }else{
                        dp[i][j]=1;
                    }
                }else{
                    dp[i][j]=Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        return dp[m][n];
    }

 

上一篇:力扣 389. 找不同 难度:简单


下一篇:leetcode刷题——无重复字符最长子串(Java)