LeetCode 1143. Longest Common Subsequence解题报告(python)

本文介绍了一种使用动态规划解决最长公共子序列问题的方法,通过详细的代码示例和解析,展示了如何计算两个字符串的最长公共子序列长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1143. Longest Common Subsequence

  1. Longest Common Subsequence python solution

题目描述

Given two strings text1 and text2, return the length of their longest common subsequence.
A 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.

在这里插入图片描述

解析

使用动态规划求解本题,
dp[i][j]代表着text1的前i 个字符和text2的前j 个字符可以计算得出的最长子字符串,需要注意的是这里的i和j并不包括在内。)下最长相同子字符串的长度。
所以动态规划的原则可以写出:
if text1[i-1]==text2[j-1]:
dp[i][j]=dp[i-1][j-1]+1
否则
dp[i][j]=max(dp[i-1][j],dp[i][j-1])

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m=len(text1)
        n=len(text2)
        dp=[[0 for _ in range(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]

Reference

https://leetcode.com/problems/longest-common-subsequence/discuss/389782/Simon’s-Note-Python3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值