• 代码随想录训练营二刷第五十八天 | 583. 两个字符串的删除操作 72. 编辑距离


    代码随想录训练营二刷第五十八天 | 583. 两个字符串的删除操作 72. 编辑距离

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

    题目链接:https://leetcode.cn/problems/delete-operation-for-two-strings/
    思路:定义dp[i][j]为要是得区间[0,i-1]和区间[0,j-1]所需要删除元素的最少个数。
    初始化的话,当word1=""时word2计算长度每走一步都要删除一个,当word2=“”时同理。
    递推公式:当word1[i-1]=word2[j-1]时,不用删除dp[i][j] = dp[i-1][j-1];当不等时,需要考虑删除word[i-1]或者word[j-1]当然得是最少个数dp[i][j] = Math.min(dp[i][j-1]+1, dp[i-1][j]+1)。

    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(); i++) {
                dp[i][0] = i;
            }
            for (int i = 0; i <= word2.length(); i++) {
                dp[0][i] = i;
            }
            for (int i = 1; i <= word1.length(); i++) {
                for (int j = 1; j <= word2.length(); j++) {
                    if (word1.charAt(i-1) == word2.charAt(j-1)) {
                        dp[i][j] = dp[i-1][j-1];
                    }else {
                        dp[i][j] = Math.min(dp[i][j-1]+1, dp[i-1][j]+1);
                    }
                }
            }
            return dp[word1.length()][word2.length()];
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    二、72. 编辑距离

    题目链接:https://leetcode.cn/problems/edit-distance/
    思路:定义dp和上题基本一致,相等时dp[i][j] = dp[i-1][j-1];
    不等时增加和删除是一个意思,而替换之后就会发生word1[i-1]=word2[j-1]那也等价于在dp[i-1][j-1]的基础上加一。

    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(); i++) {
                dp[i][0] = i;
            }
            for (int i = 0; i <= word2.length(); i++) {
                dp[0][i] = i;
            }
            for (int i = 1; i <= word1.length(); i++) {
                for (int j = 1; j <= word2.length(); j++) {
                    if (word1.charAt(i-1) == word2.charAt(j-1)){
                        dp[i][j] = dp[i-1][j-1];
                    }else {
                        dp[i][j] = Math.min(Math.min(dp[i-1][j-1], dp[i-1][j]), dp[i][j-1])+1;
                    }
                }
            }
            return dp[word1.length()][word2.length()];
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    ReadingTime-十二月
    Android数据结构和算法总结-字符串相关高频面试题算法
    HK32F030MF4P6的Linux GCC工具链开发环境
    MAC地址表泛洪攻击
    FaceNet-pytorch(fixing data imbalance-CASIA)
    开源文档编辑器ONLYOFFICE最新版7.5发布
    F28069的cpu定时器
    【笔者感悟】笔者的学习感悟【五】
    电脑入门: 路由器初学者完全教程
    axios封装
  • 原文地址:https://blog.csdn.net/qq_43511039/article/details/133874049