Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
给2个单词,求从一个单词变成另一个单词需要的步骤,有三种变换方式,插入,删除和替换。
解法:DP
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 题目汇总