• leetcode 72. Edit Distance 编辑距离(中等)


    一、题目大意

    标签: 动态规划

    https://leetcode.cn/problems/edit-distance

    给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数  。

    你可以对一个单词进行如下三种操作:

    插入一个字符
    删除一个字符
    替换一个字符

    示例 1:

    输入:word1 = “horse”, word2 = “ros”
    输出:3
    解释:
    horse -> rorse (将 ‘h’ 替换为 ‘r’)
    rorse -> rose (删除 ‘r’)
    rose -> ros (删除 ‘e’)

    示例 2:

    输入:word1 = “intention”, word2 = “execution”
    输出:5
    解释:
    intention -> inention (删除 ‘t’)
    inention -> enention (将 ‘i’ 替换为 ‘e’)
    enention -> exention (将 ‘n’ 替换为 ‘x’)
    exention -> exection (将 ‘n’ 替换为 ‘c’)
    exection -> execution (插入 ‘u’)

    提示:

    • 0 <= word1.length, word2.length <= 500
    • word1 和 word2 由小写英文字母组成

    二、解题思路

    使用一个二维数组dp[i][j],表示将第一个字符串到位置i为止,和第二个字符串到位置j为止,最多需要几步编辑。当第i位和第j位对应的字符相同时,dp[i][j]等于dp[i-1][j-1];当二者对应的字符不同时,修改的消耗是dp[i-1][j-1]+1,插入i位置/删除j位置的消耗是dp[i][j-1]+1,插入j位置/删除i位置消耗是dp[i-1][j]+1。

    三、解题方法

    3.1 Java实现

    public class Solution {
        public int minDistance(String word1, String word2) {
            int m = word1.length();
            int n = word2.length();
            int[][] dp = new int[m + 1][n + 1];
            for (int i = 0; i <= m; i++) {
                for (int j = 0; j <= n; j++) {
                    if (i == 0) {
                        dp[i][j] = j;
                    } else if (j == 0) {
                        dp[i][j] = i;
                    } else {
                        dp[i][j] = Math.min(
                            dp[i - 1][j - 1] + (word1.charAt(i - 1) == word2.charAt(j - 1) ? 0 : 1),
                            Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1)
                        );
                    }
                }
            }
            return dp[m][n];
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    四、总结小记

    • 2022/7/4 坚持每天一题
  • 相关阅读:
    机器学习实战-AdaBoost
    GCP认证考试之BigQuery专题
    Python吴恩达深度学习作业21 -- 词向量的基本操作
    WLAN部署(AC+AP)配置及常见问题记录
    @Autowired和@Resource的区别
    【408篇】C语言笔记-第九章(数据结构概述)
    硅谷甄选运营平台-笔记
    Python3 字典
    中秋特辑——3D动态礼盒贺卡(可监听鼠标移动)
    MySQL事务
  • 原文地址:https://blog.csdn.net/ln_ydc/article/details/125609181