LeetCode 1143. Longest Common Subsequence(最长公共子序列)

输入:text1 = "abcde", text2 = "ace" 
输出:3  
解释:最长公共子序列是 "ace",它的长度为 3
public int longestCommonSubsequence(String text1, String text2) {
        int n1 = text1.length(), n2 = text2.length();
        int[][] dp = new int [n1 + 1][n2 + 1];//dp[i][j]表示s1的前i个字符与s2的前j个字符的最长公共子序列的长度
        
        for(int i = 1; i <= n1; i ++) {
            for(int j = 1; j <= n2; 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[n1][n2];
    }
原创文章 626 获赞 104 访问量 32万+

猜你喜欢

转载自blog.csdn.net/gx17864373822/article/details/105415142
今日推荐