[leetcode] 动态规划-编辑距离 Java题解

题目:72. 编辑距离
题目链接:链接
难度:困难

参考代码:

class Solution {
    public int minDistance(String word1, String word2) {
        int m = word1.length();
        int n = word2.length();
        // dp[i + 1][j + 1] 表示word1[0..i]子串 转换成word2[0..j]子串所需要的最小操作次数
        int[][] dp = new int[m + 1][n + 1];

        // base case: word2 为空串时
        for (int i = 1; i <= m; i++) {
            dp[i][0] = i;
        }

        // base case: word1 为空串时
        for (int i = 1; i <= n; i++) {
            dp[0][i] = i;
        }

        // 状态转移
        // 不断地填空表格
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; 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][j - 1], dp[i - 1][j]),
                        dp[i - 1][j - 1]
                    ) + 1;
                }
            }
        }
        return dp[m][n];
    }
}