Given two strings
text1
and text2
, return the length of their longest common subsequence. 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"
.A common subsequence of two strings is a subsequence that is common to both strings.
Example 1:
Input: text1 = “abcde”, text2 = “ace”
Output: 3
Explanation: The longest common subsequence is “ace” and its length is 3.
Example 2:
Input: text1 = “abc”, text2 = “abc”
Output: 3
Explanation: The longest common subsequence is “abc” and its length is 3.
Example 3:
Input: text1 = “abc”, text2 = “def”
Output: 0
Explanation: There is no such common subsequence, so the result is 0.
Constraints:
1 <= text1.length, text2.length <= 1000
*
text1
and text2
consist of only lowercase English characters.题目大意:
求两字符串的最大公共字符序列,不一定需要连续
解题思路:
两字符串最值问题用DP
dp[i][j]为最大公共字符序列,最后一位不需要相等。递归式为:1
2dp[i][j] = dp[i - 1][j - 1] + 1 if text1[i - 1] == text2[j - 1]
= max(dp[i - 1][j], dp[i][j - 1])
解题步骤:
DP五点注意事项
注意事项:
- 不相等时候不需要dp[i - 1][j - 1],因为已经包含在dp[i - 1][j]或dp[i][j - 1]中, DP属于累计DP
Python代码:
1 | # dp[i][j] = dp[i - 1][j - 1] + 1 if text1[i - 1] == text2[j - 1] |
打印路径
Python代码:
1 | longest, res = dp[-1][-1], '' |
算法分析:
时间复杂度为O(nm)
,空间复杂度O(nm)