摘要:給定兩個字符串 text1 和 text2,返回這兩個字符串的最長公共子序列。class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: def dp(i, j): # 空串的 base case if i == -1 or j == -1: return 0 # 找到一個lcs,繼續往前找 if text1[i] == text2[j]: return dp(i - 1, j - 1) + 1 else: # 誰能讓lcs最長就聽誰的 return max(dp(i, j-1), dp(i-1, j)) # i 和 j 初始化爲最後一個索引 return dp(len(text1)-1, len(text2)-1)。

1143. 最長公共子序列

給定兩個字符串 text1 和 text2,返回這兩個字符串的最長公共子序列。

一個字符串的 子序列 是指這樣一個新的字符串:它是由原字符串在不改變字符的相對順序的情況下刪除某些字符(也可以不刪除任何字符)後組成的新字符串。

例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。兩個字符串的「公共子序列」是這兩個字符串所共同擁有的子序列。

若這兩個字符串沒有公共子序列,則返回 0。

示例 1:

輸入:text1 = "abcde", text2 = "ace"

輸出:3

解釋:最長公共子序列是 "ace",它的長度爲 3。

示例 2:

輸入:text1 = "abc", text2 = "abc"

輸出:3

解釋:最長公共子序列是 "abc",它的長度爲 3。

示例 3:

輸入:text1 = "abc", text2 = "def"

輸出:0

解釋:兩個字符串沒有公共子序列,返回 0。

提示:

1 <= text1.length <= 1000

1 <= text2.length <= 1000

輸入的字符串只含有小寫英文字符。

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m, n = len(text1), len(text2)
        # 構建 DP table 和 base case
        dp = [[0]*(n+1) for _ in range(m+1)] # m行n列
        for i in range(1, m + 1): #行
            for j in range(1, n + 1): #列
                if text1[i-1] == text2[j-1]:
                    # 找到第一個lcs
                    dp[i][j] = 1 + dp[i-1][j-1]
                else:
                    dp[i][j] = max(dp[i][j-1], dp[i-1][j])
        return dp[-1][-1]
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        def dp(i, j):
            # 空串的 base case
            if i == -1 or j == -1: 
                return 0
            # 找到一個lcs,繼續往前找
            if text1[i] == text2[j]:
                return dp(i - 1, j - 1) + 1
            else:
                # 誰能讓lcs最長就聽誰的
                return max(dp(i, j-1), dp(i-1, j))
        # i 和 j 初始化爲最後一個索引
        return dp(len(text1)-1, len(text2)-1)
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m, n = len(text1), len(text2)
        dp = [[0 for k in range(n+1)] for l in range(m+1)]
        for i in range (m+1):
            for j in range(n+1):
                if i == 0 or j == 0:
                    dp[i][j] == 0
                elif text1[i-1] == text2[j-1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                else:
                    dp[i][j] = max(dp[i][j-1], dp[i-1][j])
        return dp[-1][-1]

歡迎關注我們的微信公衆號,每天學習Go知識

相關文章