1. 程式人生 > 其它 >[leetcode] 583. Delete Operation for Two Strings

[leetcode] 583. Delete Operation for Two Strings

題目

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

Example 1:

Input: word1 = "sea", word2 = "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Example 2:

Input: word1 = "leetcode", word2 = "etco"
Output: 4

Constraints:

  • 1 <= word1.length, word2.length <= 500
  • word1 and word2 consist of only lowercase English letters.

思路

為word1和word2分別設兩個指標i、j進行遍歷,總共分為如下幾種情況:

  1. i遍歷到底且j遍歷到底:無需刪除任何字元。
  2. i遍歷到底或j遍歷到底:有一方已經遍歷到底,需刪除一方剩餘的字元。
  3. i和j所標識的字元相等:當前字元相等,無需刪除,i和j均前進一步。
  4. i和j所標識的字元不相等:分為刪除i字元或刪除j字元兩種情況,隨後刪除的一方前進一步。

程式碼

python版本:

# dfs,超時
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        def dfs(i, j):
            if i == len(word1) and j == len(word2):
                return 0
            if i == len(word1) or j == len(word2):
                return len(word1)+len(word2)-i-j
            if word1[i] == word2[j]:
                return dfs(i+1, j+1)
            return min(dfs(i+1, j), dfs(i, j+1))+1
        return dfs(0, 0)

# 優化dfs,使用輔助陣列記錄重複呼叫 1255 ms
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        helper = [[-1]*len(word2) for _ in range(len(word1))]

        def dfs(i, j):
            print(i, j)
            if i == len(word1) and j == len(word2):
                return 0
            if i == len(word1) or j == len(word2):
                return len(word1)+len(word2)-i-j
            if helper[i][j] != -1:
                return helper[i][j]
            if word1[i] == word2[j]:
                helper[i][j] = dfs(i+1, j+1)
                return helper[i][j]
            helper[i][j] = min(dfs(i+1, j), dfs(i, j+1))+1
            return helper[i][j]
        res = dfs(0, 0)
        return res

# 動態規劃 320 ms
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        dp = [[math.inf]*(len(word2)+1) for _ in range(len(word1)+1)]
        for i in range(len(dp)):
            for j in range(len(dp[i])):
                if i == 0 or j == 0:
                    dp[i][j] = i or j
                elif word1[i-1] == word2[j-1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1])+1
        return dp[-1][-1]