動態規劃——最長公共、上升子串/子序列

leetcode 718. 最長重複子數組

package com.leetcode;

/**
 * 718. 最長重複子數組
 * 給兩個整數數組 A 和 B ,返回兩個數組中公共的、長度最長的子數組的長度。
 * 示例:
 * 輸入:
 * A: [1,2,3,2,1]
 * B: [3,2,1,4,7]
 * 輸出:3
 * 解釋:
 * 長度最長的公共子數組是 [3, 2, 1] 。
 */
public class Main718 {
    public int findLength(int[] A, int[] B) {
        if(A.length == 0 || B.length == 0) {
            return 0;
        }
        int m = A.length + 1;
        int n = B.length + 1;
        int ans = 0;
        int[][] dp = new int[m][n];
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (A[i-1] == B[j-1]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                    ans = Math.max(dp[i][j], ans);
                }
            }
        }
        return ans;
    }
    public static void main(String[] args) {
        int[] A = {1,2,3,2,1};
        int[] B = {3,2,1,4,7};
        Main718 m = new Main718();
        System.out.println(m.findLength(A,B));
    }
}

leetcode 1143. 最長公共子序列

package com.leetcode;

/**
 * 1143. 最長公共子序列
 * 給定兩個字符串 text1 和 text2,返回這兩個字符串的最長公共子序列。
 * 一個字符串的 子序列 是指這樣一個新的字符串:它是由原字符串在不改變字符的相對順序的情況下刪除某些字符(也可以不刪除任何字符)後組成的新字符串。
 * 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。兩個字符串的「公共子序列」是這兩個字符串所共同擁有的子序列。
 * 若這兩個字符串沒有公共子序列,則返回 0。
 */
public class Main1143 {
    public int longestCommonSubsequence(String text1, String text2) {
        int len1 = text1.length();
        int len2 = text2.length();
        int[][] dp = new int[len1+1][len2+1];
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; 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-1][j], dp[i][j-1]);
            }
        }
        return dp[len1][len2];
    }
    public static void main(String[] args) {
        Main1143 m = new Main1143();
        String text1 = "abcde", text2 = "ace";
        System.out.println(m.longestCommonSubsequence(text1,text2));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章