"""
Given two strings text1 and text2, return the length of their longest common subsequence.
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. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
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.
""" """
提交显示wrong answer,但在IDE是对的
其实这个代码很冗余,应该是 超时
"""
class Solution1:
def longestCommonSubsequence(self, text1, text2):
res1, res2 = 0, 0
i, j = 0, 0
while i < len(text1) and j < len(text2):
if text1[i] == text2[j]:
res1 += 1
i += 1
j += 1
else:
if len(text1) - i < len(text2) - j: #第二遍循环是为了处理这个
i += 1
else:
j += 1
i, j = 0, 0
while i < len(text1) and j < len(text2):
if text1[i] == text2[j]:
res2 += 1
i += 1
j += 1
else:
if len(text1) - i > len(text2) - j:
i += 1
else:
j += 1
res = max(res1, res2)
return res """
经典的动态规划,用一个二维数组,存当前的结果
如果值相等:dp[i][j] = dp[i-1][j-1] + 1
如果值不等:dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 左边和上边的最大值
在矩阵 m行n列容易溢出,这点很难把握
目前的经验,每次严格按照行-列的顺序进行
"""
class Solution:
def longestCommonSubsequence(self, text1, text2):
n = len(text1)
m = len(text2)
dp = [[0]*(m+1) for _ in range(n+1)] #建立 n+1行 m+1列矩阵,值全为0
for i in range(1, n+1): #bug 内外循环层写反了,导致溢出,n+1 * m+1 矩阵
for j in range(1, m+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[-1][-1]