i@yujinyan.me

Blog

Longest Common Subsequence

LeetCode

Given two strings text1 and text2, return the length of their longest common subsequence.

A common subsequence of two strings is a subsequence that is common to both strings.

Example:

Input: text1 = "abcbdab", text2 = "bdcaba"
Output: 4
Explanation:
The longest common subsequence is "bcba" and its length is 4.

Code

public int longestCommonSubsequence(String text1, String text2) {
  int m = text1.length(), n = text2.length();
  int[][] dp = new int[m + 1][n + 1];
  for (int i = 1; i <= m; i++) {
    char c1 = text1.charAt(i - 1);
    for (int j = 1; j <= n; j++) {
      char c2 = text2.charAt(j - 1);
      if (c1 == c2) {
        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[m][n];
}

State transition

dp[i][j]={dp[i1][j1]+1s[i]=s[j]max(dp[i][j1],dp[i1][j])s[i]s[j]dp[i][j] = \begin{cases} dp[i - 1][j - 1] + 1 & s[i] = s[j] \\ max(dp[i][j - 1], dp[i - 1][j]) & s[i] \not = s[j] \end{cases}

Try clicking on different values to see how they are calculated.

""obdcaba
""00000000
a00000111
b00111122
c00112222
b00112233
d00122233
a00122334
b00122344

Similar problem

LeetCode