150強訪談中等

最長公共子序列

“最長公共子序列”問題的詳細指南和 Python 實作。

問題陳述

中等

給定兩個字串 text1 和 text2,傳回它們最長的公共子序列的長度。如果沒有公共子序列,則傳回0。

字串的子序列是在原始字串中刪除一些字元(可以沒有)而產生的新字串,而不改變其餘字元的相對順序。 (例如,“ace”是“abcde”的子序列)。

寫一個函數 longestCommonSubsequence(text1: str, text2: str) -> int

約束條件
  • 1 <= len(text1), len(text2) <= 1000
  • text1 and text2 consist of only lowercase English characters

範例

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 common subsequence, so the result is 0.

Need a Hint?
考慮使用 2D DP 特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。