您的位置:首页 > 其它

[LeetCode] 72. Edit Distance 编辑距离

2018-03-20 05:58 369 查看

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

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. 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')

给2个单词,求从一个单词变成另一个单词需要的步骤,有三种变换方式,插入,删除和替换。

解法:dp, dp[i][j]表示从word1的前i个字符转换到word2的前j个字符所需要的步骤。

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

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)

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++:

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 一个编辑距离

 

All LeetCode Questions List 题目汇总

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: