1143. longest common subsequence

Ideas : dynamic programming
dp[i][j]represents text1 front ibefore text2 and number of jcommon subsequence number.
Here Insert Picture Description
Time complexity: O (n- 2 )
Complexity Space: O (mn)

def longestCommonSubsequence(str1, str2) -> int:
    m, n = len(str1), len(str2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]  # 初始值
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if str1[i - 1] == str2[j - 1]:
                dp[i][j] = 1 + dp[i-1][j-1]
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        
    return dp[-1][-1]

Published 135 original articles · won praise 5 · Views 7102

Guess you like

Origin blog.csdn.net/qq_27921205/article/details/104412520