72. Edit Distance
题目描述
最小编辑距离 - 给定两个单词word1和word2,输出将word1转换成word2所需的最小操作数。定义如下三种操作:插入字符/删除字符/替换字符
例子 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’)
思想 看到最小,想到DP。 dp[i][j]表示将word1[:i]转换为word2[:j]所需的最小操作数. 如果word1[i-1] == word2[j-1],则dp[i][j] = dp[i-1][j-1]; 否则可以采取替换操作:dp[i][j] = dp[i-1][j-1] + 1;或者插入/删除操作:dp[i][j] = dp[i-1][j] + 1/ dp[i][j] = dp[i][j-1] + 1 解法
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ m, n = len(word1), len(word2) dp = [[0] * (n+1) for _ in range(m+1)] # dp[i][j]表示将word1[:i]转换成word2[:j]所需的最小操作数 for i in range(m+1): for j in range(n+1): if i == 0: dp[0][j] = j elif j == 0: dp[i][0] = i else: dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]) + 1, dp[i-1][j-1] + (word1[i-1] != word2[j-1])) return dp[-1][-1]