Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
if i == 0 且 j == 0,edit(i, j) = 0
if i == 0 且 j > 0,edit(i, j) = j
if i > 0 且j == 0,edit(i, j) = i
if i ≥ 1 且 j ≥ 1 ,edit(i, j) == min{ edit(i-1, j) + 1, edit(i, j-1) + 1, edit(i-1, j-1) + f(i, j) }
class Solution(object):
def minDistance(self, word1, word2):
n = len(word1)
m = len(word2)
dp = [[0]*(m+1) for i in range(0 , n+1)]
for i in range(0 , n+1):
for j in range(0 , m+1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
else:
k = 0
if word1[i-1] != word2[j-1]:
k = 1
dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1)
dp[i][j] = min(dp[i][j] , dp[i-1][j-1] + k)
return dp[n][m]
if __name__ == '__main__':
s = Solution()
print(s.minDistance("" , ""))