其他分享
首页 > 其他分享> > Longest Common Substring (K3)

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];
    }

 

标签:K3,String,int,text2,Substring,text1,Longest,dp,charAt
来源: https://www.cnblogs.com/feiflytech/p/15841621.html