Given two words word1 and word2, find the minimum number of operations required to convert word1to word2.
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u') 这个题目思路是用Dynamic Programming, ans[i][j] 表明前i-1 个word1的字符与到前j-1个word2的
字符的最小值, 然后ans[i][j] = min(ans[i-1][j]+ 1, ans[i][j-1] + 1, ans[i-1][j-1] + temp)
其中temp = 0 if word1[i] == word2[j] else 1
最后返回ans[m,n]即可. 这个模式跟[LeetCode] 221. Maximal Square _ Medium Tag: Dynamic Programming
很像, 都是用上, 左和左上角的元素去递推现在的元素. 当然也可以用滚动数组的方式去将space 降为 O(n) 1. Constraints
1) size >= [0*0]
2) element can be anything, captal sensitive 2. ideas
Dynamic programming, T: O(m*n) S: O(m*n) => O(n) using rolling array 3. Codes
1) S: O(m*n)
class Solution:
def editDistance(self, word1, word2):
m, n = len(word1), len(word2)
ans = [[0]*n+1 for _ in range(m+1)]
for i in range(1, m+1):
ans[i][0] = i
for j in range(1, n+1):
ans[0][j] = j
for i in range(1, m+1):
for j in range(1, n+1):
temp = 0 if word1[i-1] == word2[j-1] else 1
ans[i][j] = min(ans[i-1][j] + 1, ans[i][j-1] + 1, ans[i-1][j-1] + temp)
return ans[m][n]
2) S: O(n) using 滚动数组
class Solution:
def editDistance(self, word1, word2):
m, n = len(word1), len(word2)
ans = [[0]*(n+1) for _ in range(2)]
for j in range(1, n+1):
ans[0][j] = j
ans[1][0] = 1
for i in range(1, m+1):
for j in range(1, n+1):
ans[i%2][0] = i
temp = 0 if word1[i-1] == word2[j-1] else 1
ans[i%2][j] = min(ans[i%2-1][j] + 1, ans[i%2][j-1] + 1, ans[i%2-1][j-1] + temp)
return ans[m%2][n]
4. Test cases
1) "horse", "ros"