class Solution {
public:
int minDistance(string word1, string word2) {
}
};
72. 编辑距离
给你两个单词 word1
和 word2
, 请返回将 word1
转换成 word2
所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
示例 1:
输入:word1 = "horse", word2 = "ros" 输出:3 解释: horse -> rorse (将 'h' 替换为 'r') rorse -> rose (删除 'r') rose -> ros (删除 'e')
示例 2:
输入:word1 = "intention", word2 = "execution" 输出:5 解释: intention -> inention (删除 't') inention -> enention (将 'i' 替换为 'e') enention -> exention (将 'n' 替换为 'x') exention -> exection (将 'n' 替换为 'c') exection -> execution (插入 'u')
提示:
0 <= word1.length, word2.length <= 500
word1
和 word2
由小写英文字母组成原站题解
python3 解法, 执行用时: 92 ms, 内存消耗: 17.8 MB, 提交时间: 2023-04-19 10:22:51
class Solution: def minDistance(self, word1: str, word2: str) -> int: import functools @functools.lru_cache(None) def helper(i, j): if i == len(word1) or j == len(word2): return len(word1) - i + len(word2) - j if word1[i] == word2[j]: return helper(i + 1, j + 1) else: inserted = helper(i, j + 1) deleted = helper(i + 1, j) replaced = helper(i + 1, j + 1) return min(inserted, deleted, replaced) + 1 return helper(0, 0)
java 解法, 执行用时: 5 ms, 内存消耗: 41.4 MB, 提交时间: 2023-04-19 10:22:07
class Solution { public int minDistance(String word1, String word2) { int n = word1.length(); int m = word2.length(); // 有一个字符串为空串 if (n * m == 0) { return n + m; } // DP 数组 int[][] D = new int[n + 1][m + 1]; // 边界状态初始化 for (int i = 0; i < n + 1; i++) { D[i][0] = i; } for (int j = 0; j < m + 1; j++) { D[0][j] = j; } // 计算所有 DP 值 for (int i = 1; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { int left = D[i - 1][j] + 1; int down = D[i][j - 1] + 1; int left_down = D[i - 1][j - 1]; if (word1.charAt(i - 1) != word2.charAt(j - 1)) { left_down += 1; } D[i][j] = Math.min(left, Math.min(down, left_down)); } } return D[n][m]; } }
python3 解法, 执行用时: 140 ms, 内存消耗: 18.8 MB, 提交时间: 2023-04-19 10:21:47
''' dp[i][j] word1的前i个字符和word2的前j个字符的编辑距离 ''' class Solution: def minDistance(self, word1: str, word2: str) -> int: n = len(word1) m = len(word2) # 有一个字符串为空串 if n * m == 0: return n + m # DP 数组 D = [ [0] * (m + 1) for _ in range(n + 1)] # 边界状态初始化 for i in range(n + 1): D[i][0] = i for j in range(m + 1): D[0][j] = j # 计算所有 DP 值 for i in range(1, n + 1): for j in range(1, m + 1): left = D[i - 1][j] + 1 # 删除一个字符 down = D[i][j - 1] + 1 # 插入一个字符 left_down = D[i - 1][j - 1] # 替换一个字符 if word1[i - 1] != word2[j - 1]: left_down += 1 D[i][j] = min(left, down, left_down) return D[n][m]