代码随想录训练营二刷第五十八天 | 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()];
    }
}

二、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()];
    }
}

你可能感兴趣的:(力扣算法题,算法,动态规划,数据结构,java,leetcode)