美文网首页
LeetCode 1143. 最长公共子序列

LeetCode 1143. 最长公共子序列

作者: 陈陈chen | 来源:发表于2021-09-26 13:43 被阅读0次

1、题目

image.png

2、分析

求公共最长子序列问题,有个套路:
2.1 涉及两个字符串/数组时(比如最长公共子序列),dp 数组的含义如下:
在子数组 arr1[0..i] 和子数组 arr2[0..j] 中,我们要求的子序列(最长公共子序列)长度为 dp[i][j]。

2.2 只涉及一个字符串/数组时(比如本文要讲的最长回文子序列),dp 数组的含义如下:
在子数组 array[i..j] 中,我们要求的子序列(最长回文子序列)的长度为 dp[i][j]。

引用自:https://labuladong.github.io/zgnb/3/15/20/

这道题目,只要明确了dp数组的含义,很快就做出来了

3、代码

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

相关文章

网友评论

      本文标题:LeetCode 1143. 最长公共子序列

      本文链接:https://www.haomeiwen.com/subject/xgyqnltx.html