Longest Common Subsequence
medium
strings
dynamic-programming
Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence keeps the original left-to-right order of characters, but the chosen characters do not need to be adjacent.
Input / output
- Input:
text1: str,text2: str - Output:
int— the length of the longest subsequence common to both strings
Examples
text1 = "abcde",text2 = "ace"returns3because"ace"is a common subsequence.text1 = "abc",text2 = "abc"returns3because the entire string matches.text1 = "abc",text2 = "def"returns0because they share no characters in order.
Constraints
0 <= text1.length, text2.length <= 1000text1andtext2contain only lowercase English letters
Follow-up
How would you reconstruct one actual longest common subsequence string, not just its length? Can you reduce the dynamic-programming table from O(m * n) space to O(min(m, n)) space?
Examples
Example 1
Input: text1 = "abcde", text2 = "ace"
Output: 3
Example 2
Input: text1 = "abc", text2 = "abc"
Output: 3
Example 3
Input: text1 = "abc", text2 = "def"
Output: 0