Featured image of post 583. 两个字符串的删除操作

583. 两个字符串的删除操作

题目描述

给定两个单词 word1 和 word2 ,返回使得 word1 和  word2 相同所需的最小步数

每步 可以删除任意一个字符串中的一个字符。

示例 1:

  • 输入: word1 = “sea”, word2 = “eat”
  • 输出: 2
  • 解释: 第一步将 “sea” 变为 “ea” ,第二步将 “eat “变为 “ea”

示例  2:

  • 输入:word1 = “leetcode”, word2 = “etco”
  • 输出:4

提示:

  • 1 <= word1.length, word2.length <= 500
  • word1 和 word2 只包含小写英文字母

解法一:动态规划

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func max(nums ...int) int {
    res := nums[0]
    for _, val := range nums {
        if val > res {
            res = val
        }
    }
    return res
}

func minDistance(word1 string, word2 string) int {
    h, w := len(word1)+1, len(word2)+1
    dp := make([][]int, h)
    for i := 0; i < h; i++ {
        dp[i] = make([]int, w)
    }
    for i := 1; i < h; i++ {
        for j := 1; j < w; j++ {
            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 h + w - 2*dp[h-1][w-1] - 2
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/13 13:50:35
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计