150強訪談中等

編輯距離

“編輯距離”問題的詳細指南和 Python 實作。

問題陳述

中等

給定兩個字串 word1 和 word2,傳回將 word1 轉換為 word2 所需的最少運算元。

允許對單字進行以下三種操作:

1.插入一個字符

2.刪除一個字符

3. 替換一個字符

寫一個函數 minDistance(word1: str, word2: str) -> int

約束條件
  • 0 <= len(word1), len(word2) <= 500
  • word1 and word2 consist of lowercase English letters

範例

Example 1
Input
word1 = "horse", word2 = "ros"
Output
3
Explanation

horse -> rorse (replace 'h' with 'r') -> rose (remove 'r') -> ros (remove 'e').

Example 2
Input
word1 = "intention", word2 = "execution"
Output
5
Explanation

intention -> extention -> exention -> exection -> execution. Total 5 operations.

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 資源

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