LeetCode 1143:最长公共子序列 — 步骤可视化追踪

发布: (2026年4月9日 GMT+8 14:37)
2 分钟阅读
原文: Dev.to

Source: Dev.to

问题概述

找出两个字符串之间的最长公共子序列(LCS)的长度,子序列保持字符的相对顺序,但不要求连续。

思路

使用动态规划,构建一个二维表,其中 dp[i][j] 表示 text1i 个字符和 text2j 个字符的 LCS 长度。

  • 如果字符相同,则在对角线的值上加 1。
  • 否则,取左侧或上侧单元格的最大值。

复杂度

  • 时间复杂度: O(m·n)
  • 空间复杂度: O(m·n)

解法(Python)

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m, n = len(text1), len(text2)

        # Create a 2D dp array of size (m+1) x (n+1) and initialize it with zeros.
        dp = [[0] * (n + 1) for _ in range(m + 1)]

        # Fill in the dp array using dynamic programming.
        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])

        # The value in dp[m][n] represents the length of the LCS.
        return dp[m][n]

自己动手尝试:打开 TraceLit,逐行执行代码。

0 浏览
Back to Blog

相关文章

阅读更多 »