Loading...
Loading...
Given two strings text1 and text2, return the length of their longest common subsequence (LCS). If there is no common subsequence, return 0.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde", but "aec" is not.
A common subsequence of two strings is a subsequence that is common to both strings.
Input:
text1 — a string consisting of lowercase English letterstext2 — a string consisting of lowercase English lettersOutput:
text1 and text2Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace", which has length 3.
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" itself.
Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no character in common between the two strings, so the LCS is empty.
This is a classic Dynamic Programming problem.
Define subproblems: Let dp[i][j] represent the length of the LCS of text1[0..i-1] and text2[0..j-1].
Recurrence relation:
text1[i-1] == text2[j-1]: dp[i][j] = dp[i-1][j-1] + 1dp[i][j] = max(dp[i-1][j], dp[i][j-1])Base case: dp[0][j] = 0 and dp[i][0] = 0 for all i, j.
Result: dp[m][n] where m = len(text1) and n = len(text2).
Time Complexity: O(m × n) where m and n are the lengths of and .
0 <= text1.length, text2.length <= 1000 text1 and text2 consist of only lowercase English letters
text1text2Space Complexity: O(m × n), or O(min(m, n)) with space optimization.