博客域名:
http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/edit-distance/
题目类型:动态规划
难度评价:★★★
本文地址: http://blog.youkuaiyun.com/nerv3x3/article/details/37334113
b) Delete a character
c) Replace a character
原题页面: https://oj.leetcode.com/problems/edit-distance/
题目类型:动态规划
难度评价:★★★
本文地址: http://blog.youkuaiyun.com/nerv3x3/article/details/37334113
Given two words word1 and word2, find the minimum number of steps required to convertword1 toword2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a characterb) Delete a character
c) Replace a character
一道传统意义上的经典的动态规划题目。注意动态规划十有八九可以优化空间复杂度,不是真的要开辟一个矩阵出来。
class Solution:
# @return an integer
def minDistance(self, word1, word2):
if "" == word1 and "" == word2:
return 0
elif "" == word1:
return len(word2)
elif "" == word2:
return len(word1)
len1 = len(word1)
len2 = len(word2)
arr1 = [0 for y in range(0, len1 + 1)]
arr2 = [0 for y in range(0, len1 + 1)]
arr1[0] = 0
for y in range(1, len1 + 1):
arr1[y] = y
for x in range(1, len2 + 1):
arr2[0] = x
for y in range(1, len1 + 1):
arr2[y] = min(arr1[y - 1] + (0 if (word1[y - 1] == word2[x - 1]) else 1), arr1[y] + 1, arr2[y - 1] + 1)
tmp = arr1
arr1 = arr2
arr2 = tmp
for y in range(0, len1 + 1):
arr2[y] = 0
return arr1[len1]