• 1143. Longest Common Subsequence(Medium)


    Given two strings text1 and text2, return the length of their longest common subsequence.

    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.

    题意:

    给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。

    本文考虑动态规划的方法

    C[i,j]表示:(x1,x2,...,xi)和(y1,y2,...,yj)的最长公共子序列的长度;
    # 1143. Longest Common Subsequence
    
    class Solution:
        def longestCommonSubsequence(self, text1: str, text2: str) -> int:
            # m = len(text1)
            # n = len(text2)
            m, n = len(text1), len(text2)
    
            if text1.isspace() | text2.isspace():
                return 0
            # dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
            dp = [[0 * (n+1)] for _ in range(m+1)]
    
            for i in range(1, m+1):
                for j in range(1, n+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]
    

      

  • 相关阅读:
    python字典
    python元组
    python list列表
    deepin常用操作
    Be a child.Be a man...
    “夹心阶层”——面对高昂的房价,要面对现实,广州,除了劳动力便宜,什么都贵。
    男人一生中16件事情(转载)
    被老板臭骂了一顿,但受益匪浅。
    陪伴
    高品质生活
  • 原文地址:https://www.cnblogs.com/yancea/p/14073716.html
Copyright © 2020-2023  润新知