Skip to content

Commit 87274d5

Browse files
authored
Create 583._Delete_Operation_for_Two_Strings.md
1 parent e67517e commit 87274d5

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# 583. Delete Operation for Two Strings
2+
3+
**<font color=red>难度: Medium</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/problems/delete-operation-for-two-strings/
10+
11+
> 内容描述
12+
13+
```
14+
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.
15+
16+
Example 1:
17+
Input: "sea", "eat"
18+
Output: 2
19+
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
20+
Note:
21+
The length of given words won't exceed 500.
22+
Characters in given words can only be lower-case letters.
23+
```
24+
25+
## 解题方案
26+
27+
> 思路 1
28+
******- 时间复杂度: O(N^2)******- 空间复杂度: O(N^2)******
29+
30+
其实就是求出word1和word2的最长公共子序列lcs之后,然后对word1和word2进行删除操作直到两者都变成lcs为止所需要的步骤
31+
32+
beats 88.62%
33+
34+
```python
35+
class Solution:
36+
def minDistance(self, word1, word2):
37+
"""
38+
:type word1: str
39+
:type word2: str
40+
:rtype: int
41+
"""
42+
return len(word1+word2) - 2 * self.longestCommonSubsequence(word1, word2)
43+
44+
def longestCommonSubsequence(self, s1, s2): # O(mn)
45+
m, n = len(s1), len(s2)
46+
dp = [[0] * (n + 1) for i in range(m + 1)]
47+
for i in range(1, m + 1):
48+
for j in range(1, n + 1):
49+
if s1[i - 1] == s2[j - 1]:
50+
dp[i][j] = dp[i - 1][j - 1] + 1
51+
else:
52+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
53+
return dp[-1][-1]
54+
```

0 commit comments

Comments
 (0)