Blind 75

Longest Common Subsequence

Problem
LC 1143
Category
DP
File
blind75_LC1143LongestCommonSubsequence.java
Path
pkg5leetcode/blind75/blind75_LC1143LongestCommonSubsequence.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC1143LongestCommonSubsequence.java
Approach
2D DP on character prefixes of both strings.
Complexity
Time O(mn), Space O(mn)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC1143LongestCommonSubsequence.java
1package pkg5leetcode.blind75;2 3/*4 * Longest Common Subsequence | LC 11435 * APPROACH: 2D DP on character prefixes of both strings.6 * COMPLEXITY: Time O(mn), Space O(mn)7 */8public class blind75_LC1143LongestCommonSubsequence {9    static int longestCommonSubsequence(String text1, String text2) {10        int m = text1.length(), n = text2.length();11        int[][] dp = new int[m + 1][n + 1];12        for (int i = 1; i <= m; i++)13            for (int j = 1; j <= n; j++)14                if (text1.charAt(i - 1) == text2.charAt(j - 1))15                    dp[i][j] = dp[i - 1][j - 1] + 1;16                else17                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);18        return dp[m][n];19    }20 21    public static void main(String[] args) {22        check(longestCommonSubsequence("abcde", "ace") == 3, "case1");23        check(longestCommonSubsequence("abc", "abc") == 3, "case2");24        System.out.println("all tests passed");25    }26 27    static void check(boolean cond, String name) {28        if (!cond) throw new AssertionError("FAILED: " + name);29        System.out.println("  PASS " + name);30    }31}