# 【LeetCode】583. Delete Operation for Two Strings 解题报告（Python & C++）

1033 篇文章 81 订阅
901 篇文章 191 订阅

id： fuxuemingzhu

### 题目描述

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

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


Note:

1. The length of given words won’t exceed 500.
2. Characters in given words can only be lower-case letters.

### 解题方法

class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
_len1, _len2 = len(word1), len(word2)
dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)]
for i in range(1, len(word1) + 1):
for j in range(1, len(word2) + 1):
if word1[i-1] == word2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i][j-1], dp[i-1][j])
val = dp[-1][-1]
return _len1 - val + _len2 - val


class Solution {
public:
int minDistance(string word1, string word2) {
const int M = word1.size(), N = word2.size();
vector<vector<int>> dp(M + 1, vector<int>(N + 1, 0));
for (int i = 1; i < M + 1; i ++)
dp[i][0] = dp[i - 1][0] + 1;
for (int j = 1; j < N + 1; j ++)
dp[0][j] = dp[0][j - 1] + 1;
for (int i = 1; i < M + 1; i ++) {
for (int j = 1; j < N + 1; j ++) {
if (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[M][N];
}
};


### 日期

2018 年 4 月 4 日 —— 清明时节雪纷纷～～下雪了，惊不惊喜，意不意外？
2018 年 12 月 14 日 —— 12月过半，2019就要开始

• 0
点赞
• 1
收藏
觉得还不错? 一键收藏
• 0
评论
08-18 274
10-01 281
03-23 350

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。