|
| 1 | +## 72. Edit Distance |
| 2 | + |
| 3 | +``` |
| 4 | +Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. |
| 5 | +
|
| 6 | +You have the following three operations permitted on a word: |
| 7 | +
|
| 8 | +Insert a character |
| 9 | +Delete a character |
| 10 | +Replace a character |
| 11 | + |
| 12 | +
|
| 13 | +Example 1: |
| 14 | +
|
| 15 | +Input: word1 = "horse", word2 = "ros" |
| 16 | +Output: 3 |
| 17 | +Explanation: |
| 18 | +horse -> rorse (replace 'h' with 'r') |
| 19 | +rorse -> rose (remove 'r') |
| 20 | +rose -> ros (remove 'e') |
| 21 | +Example 2: |
| 22 | +
|
| 23 | +Input: word1 = "intention", word2 = "execution" |
| 24 | +Output: 5 |
| 25 | +Explanation: |
| 26 | +intention -> inention (remove 't') |
| 27 | +inention -> enention (replace 'i' with 'e') |
| 28 | +enention -> exention (replace 'n' with 'x') |
| 29 | +exention -> exection (replace 'n' with 'c') |
| 30 | +exection -> execution (insert 'u') |
| 31 | + |
| 32 | +
|
| 33 | +Constraints: |
| 34 | +
|
| 35 | +0 <= word1.length, word2.length <= 500 |
| 36 | +word1 and word2 consist of lowercase English letters. |
| 37 | +
|
| 38 | +``` |
| 39 | + |
| 40 | + |
| 41 | +```python |
| 42 | +class Solution: |
| 43 | + def minDistance(self, word1: str, word2: str) -> int: |
| 44 | + m = len(word1) |
| 45 | + n = len(word2) |
| 46 | + dp = [[float('inf')]*(n+1) for i in range(m+1)] |
| 47 | + # print(dp) |
| 48 | + dp[0][0]= 0 |
| 49 | + |
| 50 | + for i in range(0, m+1): |
| 51 | + for j in range(0, n+1): |
| 52 | + if i > 0 and j>0: |
| 53 | + # word1[i] == word2[j] |
| 54 | + if word1[i-1] == word2[j-1]: |
| 55 | + dp[i][j] = min(dp[i][j], dp[i-1][j-1]) |
| 56 | + else: |
| 57 | + dp[i][j] = min(dp[i][j], dp[i-1][j-1]+1) |
| 58 | + |
| 59 | + |
| 60 | + # remove word1[i] |
| 61 | + if i>0: |
| 62 | + dp[i][j] = min(dp[i][j], dp[i-1][j]+1) |
| 63 | + |
| 64 | + # remove word2[j] |
| 65 | + if j>0: |
| 66 | + dp[i][j] = min(dp[i][j], dp[i][j-1]+1) |
| 67 | + |
| 68 | + return dp[-1][-1] |
| 69 | +``` |
| 70 | + |
| 71 | + |
| 72 | +``` |
| 73 | +Runtime: 432 ms, faster than 5.22% of Python3 online submissions for Edit Distance. |
| 74 | +Memory Usage: 17.8 MB, less than 41.17% of Python3 online submissions for Edit Distance. |
| 75 | +``` |
0 commit comments