# [LeetCode] 72. Edit Distance 编辑距离

2021年09月15日 阅读数：2

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.html

You have the following 3 operations permitted on a word:python

1. Insert a character
2. Delete a character
3. Replace a character

Example 1:app

```Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
```

Example 2:post

```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')```

Python:  Time: O(n * m)  Space: O(n + m)htm

```class Solution:
# @return an integer
def minDistance(self, word1, word2):
if len(word1) < len(word2):
return self.minDistance(word2, word1)

distance = [i for i in xrange(len(word2) + 1)]

for i in xrange(1, len(word1) + 1):
pre_distance_i_j = distance[0]
distance[0] = i
for j in xrange(1, len(word2) + 1):
insert = distance[j - 1] + 1
delete = distance[j] + 1
replace = pre_distance_i_j
if word1[i - 1] != word2[j - 1]:
replace += 1
pre_distance_i_j = distance[j]
distance[j] = min(insert, delete, replace)

return distance[-1]
```

Python:  Time: O(n * m)  Space: O(n * m)blog

```class Solution:
# @return an integer
def minDistance(self, word1, word2):
distance = [[i] for i in xrange(len(word1) + 1)]
distance[0] = [j for j in xrange(len(word2) + 1)]

for i in xrange(1, len(word1) + 1):
for j in xrange(1, len(word2) + 1):
insert = distance[i][j - 1] + 1
delete = distance[i - 1][j] + 1
replace = distance[i - 1][j - 1]
if word1[i - 1] != word2[j - 1]:
replace += 1
distance[i].append(min(insert, delete, replace))

return distance[-1][-1]
```

C++：rem

```class Solution {
public:
int minDistance(string word1, string word2) {
int n1 = word1.size(), n2 = word2.size();
int dp[n1 + 1][n2 + 1];
for (int i = 0; i <= n1; ++i) dp[i][0] = i;
for (int i = 0; i <= n2; ++i) dp[0][i] = i;
for (int i = 1; i <= n1; ++i) {
for (int j = 1; j <= n2; ++j) {
if (word1[i - 1] == word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
}
}
}
return dp[n1][n2];
}
};
```

[LeetCode] 161. One Edit Distance 一个编辑距离