leetcode1143 Longest Common Subsequence
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1143 Longest Common Subsequence相关的知识,希望对你有一定的参考价值。
1 """ 2 Given two strings text1 and text2, return the length of their longest common subsequence. 3 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. 4 If there is no common subsequence, return 0. 5 Example 1: 6 Input: text1 = "abcde", text2 = "ace" 7 Output: 3 8 Explanation: The longest common subsequence is "ace" and its length is 3. 9 Example 2: 10 Input: text1 = "abc", text2 = "abc" 11 Output: 3 12 Explanation: The longest common subsequence is "abc" and its length is 3. 13 Example 3: 14 Input: text1 = "abc", text2 = "def" 15 Output: 0 16 Explanation: There is no such common subsequence, so the result is 0. 17 """ 18 19 """ 20 提交显示wrong answer,但在IDE是对的 21 其实这个代码很冗余,应该是 超时 22 """ 23 class Solution1: 24 def longestCommonSubsequence(self, text1, text2): 25 res1, res2 = 0, 0 26 i, j = 0, 0 27 while i < len(text1) and j < len(text2): 28 if text1[i] == text2[j]: 29 res1 += 1 30 i += 1 31 j += 1 32 else: 33 if len(text1) - i < len(text2) - j: #第二遍循环是为了处理这个 34 i += 1 35 else: 36 j += 1 37 i, j = 0, 0 38 while i < len(text1) and j < len(text2): 39 if text1[i] == text2[j]: 40 res2 += 1 41 i += 1 42 j += 1 43 else: 44 if len(text1) - i > len(text2) - j: 45 i += 1 46 else: 47 j += 1 48 res = max(res1, res2) 49 return res 50 51 52 """ 53 经典的动态规划,用一个二维数组,存当前的结果 54 如果值相等:dp[i][j] = dp[i-1][j-1] + 1 55 如果值不等:dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 左边和上边的最大值 56 在矩阵 m行n列容易溢出,这点很难把握 57 目前的经验,每次严格按照行-列的顺序进行 58 """ 59 class Solution: 60 def longestCommonSubsequence(self, text1, text2): 61 n = len(text1) 62 m = len(text2) 63 dp = [[0]*(m+1) for _ in range(n+1)] #建立 n+1行 m+1列矩阵,值全为0 64 for i in range(1, n+1): #bug 内外循环层写反了,导致溢出,n+1 * m+1 矩阵 65 for j in range(1, m+1): 66 if text1[i-1] == text2[j-1]: 67 dp[i][j] = dp[i-1][j-1] + 1 68 else: 69 dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 70 return dp[-1][-1]
以上是关于leetcode1143 Longest Common Subsequence的主要内容,如果未能解决你的问题,请参考以下文章
leetcode1143. Longest Common Subsequence
leetcode 1143. Longest Commom Subsequence 最长公共子序列(中等)
1143. Longest Common Subsequence