๐ŸŒ— 72. ็ผ–่พ‘่ท็ฆป

ๅžไฝ›็ซฅๅญ2022ๅนด6ๆœˆ9ๆ—ฅๅฐไบŽ 1 ๅˆ†้’Ÿ

๐ŸŒ— 72. ็ผ–่พ‘่ท็ฆป

้šพๅบฆ: ๐ŸŒ—

้—ฎ้ข˜ๆ่ฟฐ

img_27.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], dp[i - 1][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], Math.min(dp[i][j - 1], dp[i - 1][j - 1])) + 1;
                }
            }
        }
        return dp[rows][cols];
    }
}

่พ“ๅ‡บ

img_26.png

ไธŠๆฌก็ผ–่พ‘ไบŽ: 2022/6/20 ไธ‹ๅˆ8:24:47
่ดก็Œฎ่€…: liuxianzhishou