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

吞佛童子2022年6月9日小于 1 分钟

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

难度: 🌗

问题描述

img_25.png


解法

class Solution {
    public int minDistance(String word1, String word2) {
        // 思路:
        // dp[i][j] = dp[i - 1][j - 1], [i] == [j]
        // dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1
        int rows = word1.length();
        int cols = word2.length();
        int[][] dp = new int[rows + 1][cols + 1];
        // 初始化
        for(int i = 0; i <= rows; i ++) {
            dp[i][0] = i;
        }
        for(int j = 0; j <= cols; j ++) {
            dp[0][j] = j;
        }
        // dp
        for(int i = 1; i <= rows; i ++) {
            for(int j = 1; j <= cols; j ++) {
                int m = i - 1;
                int n = j - 1;
                if(word1.charAt(m) == word2.charAt(n)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + 1;
                }
            }
        }
        return dp[rows][cols];
    }
}

输出

img_24.png

上次编辑于: 2022/6/20 下午8:24:47
贡献者: liuxianzhishou