Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 82468b6

Browse files
583.两个字符串的删除操作增加Go动态规划二解法
1 parent 12f72ea commit 82468b6

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

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

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333

3434
dp[i][j]:以i-1为结尾的字符串word1,和以j-1位结尾的字符串word2,想要达到相等,所需要删除元素的最少次数。
3535

36-
这里dp数组的定义有点点绕,大家要撸清思路
36+
这里dp数组的定义有点点绕,大家要理清思路
3737

3838
2. 确定递推公式
3939

@@ -255,6 +255,8 @@ class Solution(object):
255255
```
256256
### Go:
257257
258+
动态规划一
259+
258260
```go
259261
func minDistance(word1 string, word2 string) int {
260262
dp := make([][]int, len(word1)+1)
@@ -287,6 +289,35 @@ func min(a, b int) int {
287289
return b
288290
}
289291
```
292+
293+
动态规划二
294+
295+
```go
296+
func minDistance(word1 string, word2 string) int {
297+
dp := make([][]int, len(word1) + 1)
298+
for i := range dp {
299+
dp[i] = make([]int, len(word2) + 1)
300+
}
301+
for i := 1; i <= len(word1); i++ {
302+
for j := 1; j <= len(word2); j++ {
303+
if word1[i-1] == word2[j-1] {
304+
dp[i][j] = dp[i-1][j-1] + 1
305+
} else {
306+
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
307+
}
308+
}
309+
}
310+
return len(word1) + len(word2) - dp[len(word1)][len(word2)] * 2
311+
}
312+
313+
func max(x, y int) int {
314+
if x > y {
315+
return x
316+
}
317+
return y
318+
}
319+
```
320+
290321
### Javascript:
291322

292323
```javascript

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /