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.

LeetCode 1143. Longest Common Subsequence解题报告(python)_第1张图片

解析

使用动态规划求解本题,
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)