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

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

解法:代码随想录

题目:- LeetCode

 题目和1143. Longest Common Subsequence思路一致,再得出longest common subsequence后最后多一个计算删除操作的计算。

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++) {
            for (int j = 0; j < word2.length(); j++) {
                if (word1.charAt(i) == word2.charAt(j)) {
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                } else {
                    dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]);
                }
                //System.out.print(dp[i + 1][j + 1] + " ");
            }
            //System.out.println(" ");
        }
        
        int res = word1.length() + word2.length() - 2 * dp[word1.length()][word2.length()];
        return res;
    }
}

72. 编辑距离

解法:代码随想录

题目:- LeetCode

dp[i + 1][j + 1]的含义是删除word1(0-i)和word2(0-j)所需要的最少操作。 

1. 当两个char相等,dp[i + 1][j + 1] = dp[i][j] -- 不需要任何操作。

2. 当连个char不相等

        a)增:dp[i + 1][j] + 1 在word1上增加

        b)删:dp[i][j + 1] + 1 在word2上删除,相当于在word1上增加

        c)改:dp[i][j] + 1 在word1/word2上进行一次替换操作

class Solution {
    public int minDistance(String word1, String word2) {
        int[][] dp = new int[word1.length() + 1][word2.length() + 1];
        for (int i = 0; i < dp.length; i++) dp[i][0] = i;
        for (int j = 0; j < dp[0].length; j++) dp[0][j] = j;

        for (int i = 0; i < word1.length(); i++) {
            for (int j = 0; j < word2.length(); j++) {
                if (word1.charAt(i) == word2.charAt(j))
                    dp[i + 1][j + 1] = dp[i][j];
                else {
                    dp[i + 1][j + 1] = Math.min(Math.min(dp[i + 1][j] + 1, dp[i][j + 1] + 1),
                        dp[i][j] + 1);
                }
            }
        }

        return dp[word1.length()][word2.length()];
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)