zoukankan      html  css  js  c++  java
  • 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]
    

      

  • 相关阅读:
    CF 120F Spider 树的直径 简单题
    POJ 1155 TELE 背包型树形DP 经典题
    CF 219D Choosing Capital for Treeland 树形DP 好题
    POJ 3162 Walking Race 树形DP+线段树
    HDU 2196 Computer 树形DP 经典题
    __str__()、__repr__()和__format__()
    item系列方法
    getattribute
    isinstance和issubclass
    继承方式完成包装
  • 原文地址:https://www.cnblogs.com/yancea/p/14073716.html
Copyright © 2011-2022 走看看