【代码随想录训练营】Day56-动态规划

代码随想录训练营 Day56

今日任务

583.两个字符串的删除操作
72.编辑距离
编辑距离总结
语言:Java

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

链接:https://leetcode.cn/problems/delete-operation-for-two-strings/

class Solution {
    public int minDistance(String word1, String word2) {
        //可以转化成最长子串问题
        //dp[i][j]表示以word2[i-1]结尾的子字符串和以word1[j-1]结尾的子字符串的最大公共子串长度
        int[][] dp = new int[word2.length() + 1][word1.length() + 1];
        for(int i = 1; i <= word2.length(); i++){
            for(int j = 1; j <= word1.length(); j++){
                if(word1.charAt(j - 1) == word2.charAt(i - 1)){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
                else{
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return word1.length() + word2.length() - dp[word2.length()][word1.length()] * 2;
    }
}

/*

        -   s   e   a

    -   0   0   0   0

    e   0   0   1   1

    a   0   0   1   2

    t   0   0   1   2

*/

72. 编辑距离

链接:https://leetcode.cn/problems/edit-distance/

class Solution {
    public int minDistance(String word1, String word2) {
        int[][] dp = new int[word2.length() + 1][word1.length() + 1];
        //以word1[j-1]结尾的word1子字符串和以word2[i-1]结尾的word2子字符串的最小编辑距离为dp[i][j]
        //word1删除元素=word2插入元素: dp[i][j-1]+1
        //word2删除元素=word1插入元素: dp[i-1][j]+1
        //word1或word2替换元素: dp[i-1][j-1]+1
        for(int i = 0; i <= word2.length(); i++){
            dp[i][0] = i;
        }
        for(int j = 0; j <= word1.length(); j++){
            dp[0][j] = j;
        }
        for(int i = 1; i <= word2.length(); i++){
            for(int j = 1; j <= word1.length(); j++){
                if(word1.charAt(j - 1) == word2.charAt(i - 1)){
                    dp[i][j] = dp[i - 1][j - 1];
                }
                else{
                    dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
                }
            }
        }
        return dp[word2.length()][word1.length()];
    }
}

/*

        -   h   o   r   s   e

    -   0   1   2   3   4   5 

    r   1   1   2   2   3   4

    o   2   2   1   2   3   3

    s   3   3   2   2   2   3

*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值