Skip to content

Latest commit

 

History

History
55 lines (51 loc) · 1.58 KB

072.md

File metadata and controls

55 lines (51 loc) · 1.58 KB

72. Edit Distance

Solution 1 (O(mn))

# Dynamic programming
class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        l1 = len(word1)
        l2 = len(word2)
        ans = [[0 for _ in range(l2 + 1)] for _ in range(l1 + 1)]
        for i in range(1, l1 + 1):
            ans[i][0] = i
        for i in range(1, l2 + 1):
            ans[0][i] = i
        for i in range(1, l1 + 1):
            for j in range(1, l2 + 1):
                flag = word1[i - 1] != word2[j - 1]
                ans[i][j] = min(ans[i][j - 1] + 1, ans[i - 1][j] + 1,
                                ans[i - 1][j - 1] + flag)
        return ans[l1][l2]

Solution 2 (O(mn))

# Dynamic programming
class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        l1 = len(word1)
        l2 = len(word2)
        ans = [[0 for _ in range(l2 + 1)] for _ in range(l1 + 1)]
        for i in range(1, l1 + 1):
            ans[i][0] = i
        for i in range(1, l2 + 1):
            ans[0][i] = i
        for i in range(1, l1 + 1):
            for j in range(1, l2 + 1):
                if word1[i - 1] == word2[j - 1]:
                    ans[i][j] = ans[i - 1][j - 1]
                else:
                    ans[i][j] = 1 + min(ans[i][j - 1], ans[i - 1][j],
                                        ans[i - 1][j - 1])
        return ans[l1][l2]