leetcode-1143-Longest-Common-Subsequence

描述


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:

1
2
3
Input: text1 = "abcde", text2 = "ace" 
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:

1
2
3
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

1
2
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[i][j] 表示 text1 的前 i 个字符和 text2 的前 j 个字符,当 text1[i-1]==text2[j-1], dp[i][j]=dp[i-1][j-1]+1, 否则 dp[i][j] = max(dp[i-1][j], dp[i][j-1])

解决方案1(Python)


1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
text1_length, text2_length = len(text1), len(text2)

dp = [[0] * (text2_length+1) for _ in range(text1_length+1)]

for i in range(1, text1_length+1):
for j in range(1, text2_length+1):
if text1[i-1] == text2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[text1_length][text2_length]

解决方案2(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func longestCommonSubsequence(text1 string, text2 string) int {
text1_length, text2_length := len(text1), len(text2)
dp := make([][]int, text1_length+1)
for i := range dp {
dp[i] = make([]int, text2_length+1)
}

for i, ch1 := range(text1) {
for j, ch2 := range(text2) {
if ch1 == ch2 {
dp[i+1][j+1] = dp[i][j] + 1
} else {
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
}
}
}
return dp[text1_length][text2_length]
}

func max(a, b int) int {
if a > b {
return a
}
return b
}

相关问题


题目来源