Q:
给定两个单词 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')
链接:https://leetcode-cn.com/problems/edit-distance/description/
思路:
整个程序就是动态规划状态矩阵填充的过程 ,首先第一行和第一列都好解释,因为两个字符串都可以删除至空值“”,然后相等,但是这不是我们想要的,对于res[i][j]的每一个值,他的产生取决于三个方向,也就是他的左边,上面,和对角线,并且都有不同的含义,我的理解是,左边可以表示插入,上面表示删除,对角线表示替换,举个例子:
S | a | t | u | r | d | a | y | ||
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
S | 1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
u | 2 | 1 | 1 | 2 | 2 | 3 | ? | ||
n | |||||||||
d | |||||||||
a | |||||||||
y |
问号位置也就是res[2][6]所在位置,他的值取决于上面的5 左面的3,和对角线的4,具体怎么来的呢,上面的5代表:由"S"到"Saturd"需要5个操作数,也就是直接添加aturd一共五个字符,左面的3表示由“Saturd“到“Su“所需的操作数,也就是逐一删除atd,因为为啥说上面是插入左边是删除,是因为上面的值代表从短的字符串Su扩展到一个长的Saturd,而左面则是从Saturd删除至Su,因此期间肯定有插入和删除的操作,至于说斜对角,则存在替换的操作,因此对于一个res[i][j],其值取决于3个值之间的最小值,也就是代码迭代的核心:
res[i][j] = min(res[i - 1][j] + 1, res[i][j - 1] + 1)
if word1[i - 1] == word2[j - 1]:
cost = 0
else:
cost = 1
res[i][j] = min(res[i][j], res[i - 1][j - 1] + cost)
代码:
class Solution:
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
n = len(word1)
m = len(word2)
res = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
for i in range(n+1):
res[i][0] = i
for j in range(m+1):
res[0][j] = j
for i in range(1, n+1):
for j in range(1, m+1):
res[i][j] = min(res[i - 1][j] + 1, res[i][j - 1] + 1)
if word1[i - 1] == word2[j - 1]:
cost = 0
else:
cost = 1
res[i][j] = min(res[i][j], res[i - 1][j - 1] + cost)
return res[n][m]