Skip to content

Commit baff820

Browse files
committed
添加 (0583.两个字符串的删除操作.md) : 增加解题思路
1 parent 85bd6fa commit baff820

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

problems/0583.两个字符串的删除操作.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
## 思路
2020

21+
### 动态规划一
22+
2123
本题和[动态规划:115.不同的子序列](https://programmercarl.com/0115.不同的子序列.html)相比,其实就是两个字符串都可以删除了,情况虽说复杂一些,但整体思路是不变的。
2224

2325
这次是两个字符串可以相互删了,这种题目也知道用动态规划的思路来解,动规五部曲,分析如下:
@@ -98,6 +100,29 @@ public:
98100
99101
```
100102

103+
### 动态规划二
104+
105+
本题和[动态规划:1143.最长公共子序列](https://programmercarl.com/1143.最长公共子序列.html)基本相同,只要求出两个字符串的最长公共子序列长度即可,那么除了最长公共子序列之外的字符都是必须删除的,最后用两个字符串的总长度减去两个最长公共子序列的长度就是删除的最少步数。
106+
107+
代码如下:
108+
109+
```CPP
110+
class Solution {
111+
public:
112+
int minDistance(string word1, string word2) {
113+
vector<vector<int>> dp(word1.size()+1, vector<int>(word2.size()+1, 0));
114+
for (int i=1; i<=word1.size(); i++){
115+
for (int j=1; j<=word2.size(); j++){
116+
if (word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
117+
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
118+
}
119+
}
120+
return word1.size()+word2.size()-dp[word1.size()][word2.size()]*2;
121+
}
122+
};
123+
124+
```
125+
101126
## 其他语言版本
102127
103128

0 commit comments

Comments
 (0)