编辑距离
作者:互联网
给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。
def minDistance(word1, word2):
n1 = len(word1)
n2 = len(word2)
if n1 * n2 == 0:
return n1 + n2
m = [[0 for i in range(n1+1)] for j in range(n2+1)]
for i in range(1, n1+1):
m[0][i] = m[0][i - 1] + 1
for j in range(1, n2+1):
m[j][0] = m[j - 1][0] + 1
for i in range(1, n1+1):
for j in range(1, n2+1):
dis1 = m[j][i - 1] + 1
dis2 = m[j - 1][i] + 1
dis3 = m[j - 1][i - 1] + int(word1[i - 1] != word2[j - 1])
m[j][i] = min(dis1, dis2, dis3)
return m[n2][n1]
标签:dis2,距离,编辑,range,word1,word2,n1,n2 来源: https://www.cnblogs.com/youguang369/p/15408208.html