Leetcode 583 Solution

This article provides solution to leetcode question 583 (delete-operation-for-two-strings)

https://leetcode.com/problems/delete-operation-for-two-strings

Solution

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m = len(word1)
        n = len(word2)

        if not m or not n:
            return m + n

        dp = [[0] * n for _ in range(m)]

        ans = dp[0][0] = 1 if word1[0] == word2[0] else 0
        for i in range(1, m):
            dp[i][0] = 1 if word1[i] == word2[0] else dp[i - 1][0]
            ans = max(ans, dp[i][0])

        for j in range(1, n):
            dp[0][j] = 1 if word1[0] == word2[j] else dp[0][j - 1]
            ans = max(ans, dp[0][j])

        for i in range(1, m):
            for j in range(1, n):
                if word1[i] == word2[j]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                dp[i][j] = max(dp[i][j], dp[i - 1][j], dp[i][j - 1])
                ans = max(ans, dp[i][j])

        return m + n - 2 * dp[-1][-1]