我是靠谱客的博主 缥缈冷风,最近开发中收集的这篇文章主要介绍LeetCode 1143. Longest Common Subsequence解题报告(python),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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

最后

以上就是缥缈冷风为你收集整理的LeetCode 1143. Longest Common Subsequence解题报告(python)的全部内容,希望文章能够帮你解决LeetCode 1143. Longest Common Subsequence解题报告(python)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(88)

评论列表共有 0 条评论

立即
投稿
返回
顶部