Leetcode 1143. Longest Common Subsequence

Problem

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

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.

  • For example, “ace” is a subsequence of “abcde”.

A common subsequence of two strings is a subsequence that is common to both strings.

Algorithm

Dynamic Programming (DP). Define state f(i, j) is the common subsequence of text1[0…i] and text2[0…j], so we have
f ( i , j ) = { f ( i − 1 , j − 1 ) + 1 if  s [ l e f t ] = = s [ r i g h t ] max ⁡ [ f ( i − 1 , j ) , f ( i , j − 1 ) ] otherwise f(i, j) = \begin{cases} f(i-1, j-1) + 1 & \text{if } s[left] == s[right ]\\ \max[f(i-1, j), f(i, j-1)] & \text{otherwise} \end{cases} f(i,j)={f(i1,j1)+1max[f(i1,j),f(i,j1)]if s[left]==s[right]otherwise

Code

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        slen1 = len(text1)
        slen2 = len(text2)
        if not slen1 or not slen2:
            return 0
        
        dp = [[0] * (slen2 + 1) for i in range(slen1 + 1)]
        for i in range(1, slen1 + 1):
            for j in range(1, slen2 + 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[slen1][slen2]
  • 18
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值