From 1c4b9a252fd004a9ec3771b6dbfc707818e4f1d4 Mon Sep 17 00:00:00 2001 From: matthew <1123957599@qq.com> Date: Sat, 6 Apr 2024 10:38:12 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00583=20=E4=B8=A4=E4=B8=AA?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E7=9A=84=E5=88=A0=E9=99=A4=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=20Python=E8=A7=A3=E6=B3=952?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0583.两个字符串的删除操作.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0583.两个字符串的删除操作.md b/problems/0583.两个字符串的删除操作.md index 7dbb8ef5..4816c37c 100644 --- a/problems/0583.两个字符串的删除操作.md +++ b/problems/0583.两个字符串的删除操作.md @@ -234,6 +234,25 @@ class Solution: return dp[-1][-1] ``` +> 版本 2 + +```python +class Solution(object): + def minDistance(self, word1, word2): + m, n = len(word1), len(word2) + + # dp 求解两字符串最长公共子序列 + dp = [[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]: + dp[i][j] = dp[i-1][j-1] + 1 + else: + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + + # 删去最长公共子序列以外元素 + return m + n - 2 * dp[-1][-1] +``` ### Go: ```go