每天坚持刷题!!!
今天继续死磕难题
leetcode 72. 编辑距离
题目描述:
给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
1. 插入一个字符
2. 删除一个字符
3. 替换一个字符
题目分析:
1. 动态规划的题的难点还是如何定义状态转移方程和暂存的数组,对于这一道题而言,暂存的二维数组D[i][j]为word1到第i个字符为止匹配word2到第j个字符为止的所需最小的操作数
2. 状态转移分析如下:首先如果word1[i] == word2[j],那么 D[i][j] == D[i-1][j-1],如果word1[i] != word2[j],那么最小的操作数量可能为D[i-1][j-1] + 1(替换操作),或者D[i][j-1] + 1(删除操作),或者D[i-1][j] + 1(插入操作)这三者的最小值。
def minDistance(word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
if not word1 and not word2:
return 0
elif not word1:
return len(word2)
elif not word2:
return len(word1)
temp = [[0 for _ in word2] for _ in word1]
temp[0][0] = 1 if word1[0] != word2[0] else 0
for i in xrange(len(word1)):
for j in xrange(len(word2)):
if i == j == 0:
continue
if i - 1 >=0 and j - 1>=0:
if word1[i] == word2[j]:
temp[i][j] = temp[i-1][j-1]
else:
temp[i][j] = min(temp[i-1][j-1] + 1, temp[i][j-1] + 1, temp[i-1][j] + 1)
elif i - 1 >= 0:
if word1[i] == word2[j]:
temp[i][j] = i
else:
temp[i][j] = temp[i-1][j] + 1
elif j - 1 >= 0:
if word1[i] == word2[j]:
temp[i][j] = j
else:
temp[i][j] = temp[i][j-1] + 1
return temp[-1][-1]
欢迎大家批评指正!