Permutation Sequence @ LeetCode (Python)
Reorder List @ LeetCode (Python)

Edit Distance @ LeetCode (Python)

kitt posted @ 2014年4月06日 19:24 in LeetCode , 3385 阅读

动态规划。看了水中的鱼的解题报告, dp[i][j]表示word1前i个字母变成word2前j个字母的步数(edit distance)。如果word1的第i个字母等于word2的第j个字母, 则dp[i][j] = dp[i-1][j-1]。如果不等, 则有三种情况:

1) 把word1的前i-1个字母变成word2的前j-1个字母, 再把word1的第i个字母换成word2的第j个字母, 即dp[i-1][j-1] + 1

2) 把word1的前i个字母变成word2的前j-1个字母, 再加上word2的第j个字母, 即dp[i][j-1] + 1

3) 删掉word1的第i个字母, 把word1的前i-1个字母变成word2的前j个字母, 即1 + dp[i-1][j]

三种情况的最小值就是dp[i][j]。初始情况: dp[i][0] = i (0 <= i <= word1 length), dp[0][j] = j (0 <= j <= word2 length).

 

Dynamic programming. Let dp[i][j] indicate the steps (edit distance) of changing word1's first i letters to word2's first j letters. If word1's ith letter equals to word2's jth letter, then dp[i][j] = dp[i-1][j-1]. If not, 3 cases:

1) Change word1's first i-1 letters to word2's j-1 letters, then change word1's ith letter to word2's jth letter, i.e. dp[i-1][j-1] + 1

2) Change word1's first i letters to word2's first j-1 letters, then add word2's jth letter, i.e. dp[i][j-1] + 1

3) Delete word1's ith letter, then change word1's first i-1 letters to word2's first j letters, i.e. 1 + dp[i-1][j]

dp[i][j] is the min value of the above 3 cases. Initialization: dp[i][0] = i (0 <= i <= word1 length), dp[0][j] = j (0 <= j <= word2 length).

class Solution:
    # @return an integer
    def minDistance(self, word1, word2):
        len1 = len(word1)
        len2 = len(word2)
        # initialization
        dp = [ [0 for j in xrange(len2 + 1)] for i in xrange(len1 + 1) ]
        for i in xrange(len1 + 1):
            dp[i][0] = i
        for j in xrange(len2 + 1):
            dp[0][j] = j
        # dp
        for i in xrange(1, len1 + 1):
            for j in xrange(1, len2 + 1):
                dp[i][j] = dp[i-1][j-1] if word1[i-1] == word2[j-1] else min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
        return dp[len1][len2]
Avatar_small
zhidan 说:
2014年9月22日 19:39

看了这么多文章,在这里看懂的。谢谢你

Avatar_small
Hackson 说:
2014年11月15日 16:30

Same here! Thanks a lot


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter