Tuesday, June 28, 2022

1143. Longest Common Subsequence

 一刷 06/2022

Version #1 DP - 2D array

This can be optimized to 1D array

Time O(MN)

Space O(MN)

Runtime: 19 ms, faster than 59.45% of Java online submissions for Longest Common Subsequence.
Memory Usage: 46.8 MB, less than 17.45% of Java online submissions for Longest Common Subsequence.

class Solution {

    public int longestCommonSubsequence(String text1, String text2) {

        // dp[i][j] the longest common subsequence with text1 [0, i) and text2 [0, j)

        // dp[i][j] = dp[i - 1][j], dp[i][j - 1] -> we don't match

        //          (text1.charAt(i - 1) == text2.charAt(j - 1)) + dp[i - 1][j - 1]

        int[][] dp = new int[text1.length() + 1][text2.length() + 1];

        for (int i = 1; i <= text1.length(); i++) {

            for (int j = 1; j <= text2.length(); j++) {

                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);

                dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + (text1.charAt(i - 1) == text2.charAt(j - 1) ? 1 : 0));

                // System.out.printf("dp[%d][%d]=%d\n", i, j, dp[i][j]);

            }

        }

        return dp[text1.length()][text2.length()];

    }

}

No comments:

Post a Comment