72. Edit Distance
# Hard (非常经典,一定要会)
Solution:
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
# two-sequence DP problem
# initialize minDis, minDis[i][j] means min distance from word1[:i+1] to word2[:j+1]
minDis = [[float('Inf')]*(len(word2)+1) for i in range(len(word1)+1)]
for i in range(len(word1)+1):
minDis[i][0] = i
for j in range(len(word2)+1):
minDis[0][j] = j
# compute
for i in range(1, len(word1)+1):
for j in range(1, len(word2)+1):
minDis[i][j] = min(minDis[i-1][j], minDis[i][j-1]) + 1
if word1[i-1] == word2[j-1]:
minDis[i][j] = min(minDis[i][j], minDis[i-1][j-1])
else:
minDis[i][j] = min(minDis[i][j], minDis[i-1][j-1]+1)
return minDis[len(word1)][len(word2)]pLast updated