【Leetcode_總結】 583. 兩個字串的刪除操作 - python
阿新 • • 發佈:2018-12-31
Q:
給定兩個單詞 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步數,每步可以刪除任意一個字串中的一個字元。
示例 1:
輸入: "sea", "eat" 輸出: 2 解釋: 第一步將"sea"變為"ea",第二步將"eat"變為"ea"
連結:https://leetcode-cn.com/problems/delete-operation-for-two-strings/description/
思路:這道題目是求最長子串(有序但不必須連續),而不是最長子序列(要求連續),因此還是使用動態規劃的方法,陣列res用來統計最長子串的大小,然後返回值是兩個字串減去子串的長度
s | e | a | ||
0 | 0 | 0 | 0 | |
e | 0 | 0 | 1 | 1 |
a | 0 | 0 | 1 | 2 |
t | 0 | 0 | 1 | 2 |
程式碼:
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ m = len(word1) n = len(word2) if m == 0 or n == 0: return abs(m - n) res = [[0] * (n+1) for _ in range(m+1)] for i in range(1,m+1): for j in range(1,n+1): if word1[i-1] == word2[j-1]: res[i][j] = res[i-1][j-1] + 1 else: res[i][j] = max(res[i - 1][j], res[i][j - 1]) return abs(m+n - 2 * res[-1][-1])