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]

相关推荐

  1. Leetcode 1143. Longest Common Subsequence

    2024-07-11 05:28:02       26 阅读
  2. leetcode1146--快照数组

    2024-07-11 05:28:02       34 阅读
  3. LeetCode 1193, 45, 48

    2024-07-11 05:28:02       29 阅读
  4. LeetCode1143. Longest Common Subsequence——动态规划

    2024-07-11 05:28:02       41 阅读
  5. Leetcode 1143 最长公共子序列

    2024-07-11 05:28:02       43 阅读
  6. Leetcode 1143:最长公共子序列

    2024-07-11 05:28:02       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 05:28:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 05:28:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 05:28:02       58 阅读
  4. Python语言-面向对象

    2024-07-11 05:28:02       69 阅读

热门阅读

  1. 从像素角度出发使用OpenCV检测图像是否为彩色

    2024-07-11 05:28:02       27 阅读
  2. ES索引模板

    2024-07-11 05:28:02       20 阅读
  3. ”极大似然估计“和”贝叶斯估计“思想对比

    2024-07-11 05:28:02       24 阅读
  4. 理解Gunicorn:Python WSGI服务器的基石

    2024-07-11 05:28:02       24 阅读
  5. C++函数模板学习

    2024-07-11 05:28:02       19 阅读
  6. 探索Perl的自动清洁工:垃圾收集机制全解析

    2024-07-11 05:28:02       21 阅读
  7. Kruskal

    2024-07-11 05:28:02       23 阅读
  8. C++入门

    C++入门

    2024-07-11 05:28:02      21 阅读
  9. Spring框架配置进阶_自动装配(XML和注解)

    2024-07-11 05:28:02       21 阅读