day50 1143.最长公共子序列 1035.不相交的线 53. 最大子序和 392.判断子序列

1143. 最长公共子序列

提示

给定两个字符串 text1text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0

一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。

  • 例如,"ace""abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。

两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。

示例 1:

复制代码
输入:text1 = "abcde", text2 = "ace" 
输出:3  
解释:最长公共子序列是 "ace" ,它的长度为 3 。

示例 2:

复制代码
输入:text1 = "abc", text2 = "abc"
输出:3
解释:最长公共子序列是 "abc" ,它的长度为 3 。

示例 3:

复制代码
输入:text1 = "abc", text2 = "def"
输出:0
解释:两个字符串没有公共子序列,返回 0 。
python 复制代码
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        maxlen=max(len(text1),len(text2))
        dp=[[0 for i in range(len(text2))] for j in range(len(text1))]
        if text1[0]==text2[0]:
                dp[0][0]=1
        for j in range(1,len(text2)):
            if text1[0]==text2[j]:
                dp[0][j]=1
            else:
                dp[0][j]=dp[0][j-1]
        for i in range(1,len(text1)):
            if text1[i]==text2[0]:
                dp[i][0]=1
            else:
                dp[i][0]=dp[i-1][0]
        for i in range(1,len(text1)):
            for j in range(1,len(text2)):
                if text1[i]==text2[j]:
                    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]
#简化版本
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        # 创建一个二维数组 dp,用于存储最长公共子序列的长度
        dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
        
        # 遍历 text1 和 text2,填充 dp 数组
        for i in range(1, len(text1) + 1):
            for j in range(1, len(text2) + 1):
                if text1[i - 1] == text2[j - 1]:
                    # 如果 text1[i-1] 和 text2[j-1] 相等,则当前位置的最长公共子序列长度为左上角位置的值加一
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    # 如果 text1[i-1] 和 text2[j-1] 不相等,则当前位置的最长公共子序列长度为上方或左方的较大值
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
        
        # 返回最长公共子序列的长度
        return dp[len(text1)][len(text2)]
相关推荐
shangjian0074 分钟前
AI大模型-机器学习-算法-线性回归
人工智能·算法·机器学习
2301_8002561117 分钟前
B+树:数据库的基石 R树:空间数据的索引专家 四叉树:空间划分的网格大师
数据结构·数据库·b树·机器学习·postgresql·r-tree
独自破碎E17 分钟前
【队列】按之字形顺序打印二叉树
leetcode
mjhcsp19 分钟前
C++ KMP 算法:原理、实现与应用全解析
java·c++·算法·kmp
lizhongxuan20 分钟前
Manus: 上下文工程的最佳实践
算法·架构
码农幻想梦23 分钟前
第九章 高级数据结构
数据结构
AlenTech24 分钟前
206. 反转链表 - 力扣(LeetCode)
数据结构·leetcode·链表
踩坑记录24 分钟前
leetcode hot100 438. 找到字符串中所有字母异位词 滑动窗口 medium
leetcode·职场和发展
CS创新实验室32 分钟前
《计算机网络》深入学:海明距离与海明码
计算机网络·算法·海明距离·海明编码
WW_千谷山4_sch34 分钟前
MYOJ_10599:CSP初赛题单10:计算机网络
c++·计算机网络·算法