72.Edit Distance
72. Edit Distance
題目描述
Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
範例
Example 1:
Example 2:
Constraints:
- 0 <=
word1.length
, word2.length
<= 500
word1
and word2
consist of lowercase English letters.
解答
C++
思路:
- 把word1變成word2, 有增刪改三種動作可以做, 求最小的操作次數
- 思考基本case
2.1. 當word1 or word2其中之一為空, 則次數為非空者的長度
2.2. 當前雙方第一個字符相同, 則考慮word1[1:]及word2[1:] substring的minDistance
2.3. 當前雙方第一個字符不同, 三種動作可做:
- 增: 接下來只需考慮word1[:] 及word2[1:]的maxDistance
- 刪: 接下來只需考慮word1[1:]及word2[:]的maxDistance
- 改: 接下來只需考慮word1[1:]及word2[1:]的maxDistance
- 避免解重複substring的maxDistance用DP
- 用類似Longest common subsequence作法, 每次多考慮word1 or word2 一個字符, 根據2.的條件計算DP
Time:
Extra Space:
XD Feb 27, 2023
Reference
回到題目列表