Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is formed by deleting some (or no) characters without disturbing the remaining characters' relative order.
If there is no common subsequence, return 0.
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
We build a 2D DP table where dp[i][j] represents the length of the LCS of the first i characters of
text1 and the first j characters of text2.
- Base case: dp[0][j] = 0 and dp[i][0] = 0 for all i, j (empty string has LCS of length 0).
- If characters match: dp[i][j] = dp[i-1][j-1] + 1.
- If characters don't match: dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
- The answer is dp[m][n].
public class LongestCommonSubsequence {
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++) {
for (int j = 1; j <= n; 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[m][n];
}
}
Complexity Analysis:
Time complexity: O(m * n) where m and n are the lengths of the two strings.
Space complexity: O(m * n) for the DP table.