#583 Delete Operation for Two Strings

Description

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

Examples

Example 1:

Input: word1 = “sea”, word2 = “eat”
Output: 2
Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.

Example 2:

Input: word1 = “leetcode”, word2 = “etco”
Output: 4

Constraints:

1 <= word1.length, word2.length <= 500
word1 and word2 consist of only lowercase English letters.

思路

感觉DP的题目就需要上天的指引,有时候表格的构建和表格里单元格的意义就直接跑到脑子里了,再然后状态转移公式也跑到脑子里了,以题目给出的sea和eat为例,每个单元格里面的内容表示 word1.substring(0, i) 和 word2.substring(0, j) 的 min delete operation steps

-0sea
00123
e1212
a2321
t3432

状态转移公式分两种情况讨论

  • word1[i] != word2[j]
    dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + 1
  • word1[i] = word2[j]
    dp[i][j] = min(dp[i][j], dp[i-1][j-1])

物理意义也比较好解释

  • 如果不理会 word1[i] 和 word2[j] 的关系,那么我们要么对word1[i]进行delete操作,然后加上dp[i-1][j],要么对word2[j]进行delete操作,然后加上dp[i][j-1]
  • 如果word1[i] = word2[j],那么delete step就是 dp[i-1][j-1],word1[i] 和 word2[j] 相同,不用delete操作
  • 三种情况取最小的那个作为min delete step

代码

class Solution {
    public int minDistance(String word1, String word2) {
        int dp[][] = new int[word1.length() + 1][word2.length() + 1];
        for (int i = 0; i < word1.length() + 1; i++)
            dp[i][0] = i;
        for (int j = 0; j < word2.length() + 1; j++)
            dp[0][j] = j;
        
        for (int i = 1; i < word1.length() + 1; i++){
            for (int j = 1; j < word2.length() + 1; j++){
                dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + 1;
                if (word1.charAt(i - 1) == word2.charAt(j - 1))
                    dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i][j]);
            }
        }
        
        return dp[word1.length()][word2.length()];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值