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];
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章