Longest Common Subsequence 解題教學:3 種解法完整比較|LeetCode 1143 Best Practice

Longest Common Subsequence 解題教學示意圖|LeetCode 1143

本文完整拆解 LeetCode 1143 Longest Common Subsequence 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Longest Common Subsequence 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


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.

 

Example 1:

Input: text1 = "abcde", text2 = "ace" 
Output: 3  
Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:

Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

 

Constraints:

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 consist of only lowercase English characters.

Python

				
					# time complexity: O(n*m)
# space compleixty: O(n*m)
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        dpGrid = [[0] * (len(text2) + 1) for _ in range(len(text1)+1)]
        for col in reversed(range(len(text2))):
            for row in reversed(range(len(text1))):
                if text2[col] == text1[row]:
                    dpGrid[row][col] = 1 + dpGrid[row+1][col+1]
                else:
                    dpGrid[row][col] = max(
                        dpGrid[row+1][col], dpGrid[row][col+1])
        return dpGrid[0][0]


text1 = "abcde"
text2 = "ace"
print(Solution().longestCommonSubsequence(text1, text2))
				
			

Longest Common Subsequence 解題思路

兩個字串的最長共同子序列是經典的二維 DP:比較 text1[i-1] 與 text2[j-1],相同就在 dp[i-1][j-1] 上加一,不同就取 dp[i-1][j] 與 dp[i][j-1] 的較大者。由於每一列只依賴上一列,可以用滾動陣列把空間從 O(m·n) 壓到 O(min(m,n))。

Longest Common Subsequence 演算法步驟

  1. 建立 (m+1)×(n+1) 的表格 dp,第 0 列與第 0 行全為 0。
  2. 雙層迴圈走訪 i 從 1 到 m、j 從 1 到 n。
  3. 若 text1[i-1] 等於 text2[j-1],令 dp[i][j] = dp[i-1][j-1] + 1。
  4. 否則令 dp[i][j] = max(dp[i-1][j], dp[i][j-1]),最後回傳 dp[m][n]。

Longest Common Subsequence 複雜度分析

項目複雜度
時間複雜度O(m·n)
空間複雜度O(min(m,n))

需要填滿 m×n 個狀態,時間為 O(m·n)。使用滾動陣列只保留一列,空間降為 O(min(m,n))——把較短的字串放在內層迴圈可讓空間更省。

Longest Common Subsequence 的邊界情況與常見錯誤

  • 索引偏移一格是最常見的錯誤,dp 的索引比字串索引多 1。
  • 任一字串為空時答案為 0,第 0 列與第 0 行的初始化已涵蓋。
  • 子序列不要求連續,與最長共同子字串是不同的題目。
  • 要還原序列的話必須保留完整二維表格,不能用滾動陣列。

Longest Common Subsequence 其他解法比較

解法時間空間說明
純遞迴列舉O(2^(m+n))O(m+n)指數爆炸
二維 DP 表格O(m·n)O(m·n)可還原序列
滾動陣列 DPO(m·n)O(min(m,n))本文採用