原题
给出两个单词word1和word2,计算出将word1转换为word2的最少操作次数。
你总共三种操作方法:
- 插入一个字符
- 删除一个字符
- 替换一个字符
样例
给出 work1="mart" 和 work2="karma"
返回 3
解题思路
- 上面的例子 mart => kart => karm => karma
- 求最少步骤 + 给出两个字符串 => Dynamic Programing (Two Sequence DP)
- 状态:cache[i][j] 表示字符串a[1]-a[i]转换为b[1]-b[i]的编辑距离,在一个二维矩阵中cache[i][j]只与其左上,左和上三个位置的值有关,分别是cache[i - 1][j - 1], cache[i][j - 1]和cache[i - 1][j]
- 当word1[i] == word2[j]的时候:
cache[j][i] = min(cache[j - 1][i - 1], cache[j - 1][i] + 1, cache[j][i - 1] + 1)
- 不等于的时候
cache[j][i] = min(cache[j - 1][i - 1], cache[j - 1][i], cache[j][i - 1]) + 1
- 起始、边界值
DP[0][j] = j: word1为空,要转化到word2[1:j],需要添加j个字符。
DP[i][0] = i: word2为空,要从word1转化到空字符串,需要删除i个字符。
(另外一个,举例子也比较清楚的](http://www.dreamxu.com/books/dsa/dp/edit-distance.html)
完整代码
class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
if not word1:
return len(word2)
if not word2:
return len(word1)
cache = [[0 for i in range(len(word1) + 1)] for j in range(len(word2) + 1)]
for i in range(1, len(word1) + 1):
cache[0][i] = i
for j in range(1, len(word2) + 1):
cache[j][0] = j
for j in range(1, len(word2) + 1):
for i in range(1, len(word1) + 1):
if word1[i - 1] == word2[j - 1]:
cache[j][i] = min(cache[j - 1][i - 1], cache[j - 1][i] + 1, cache[j][i - 1] + 1)
else:
cache[j][i] = min(cache[j - 1][i - 1], cache[j - 1][i], cache[j][i - 1]) + 1
return cache[len(word2)][len(word1)]