Edit Distance

Problem: Edit Distance

We use dynamic programming to solve this problem. We construct a 2D dynamic programming matrix and judge on edit distance of all substrings of two strings start from first character. Some special conditions we need to deal with is when 2 new letters are the same.

Code in Python:

class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        if word1 == word2: return 0
        if word1 == "": return len(word2)
        if word2 == "": return len(word1)
        dp = [[0] * len(word2) for _ in xrange(len(word1))]
        for i, c1 in enumerate(word1):
            for j, c2 in enumerate(word2):
                if not i and not j:
                    dp[i][j] = 0 if c1 == c2 else 1
                elif not i:
                    dp[i][j] = dp[i][j-1] if c1 == c2 and c1 not in word2[:j] else dp[i][j-1] + 1
                elif not j:
                    dp[i][j] = dp[i-1][j] if c1 == c2 and c2 not in word1[:i] else dp[i-1][j] + 1
                else:
                    if c1 == c2: dp[i][j] = dp[i-1][j-1]
                    else: dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1
        return dp[-1][-1]

results matching ""

    No results matching ""