• 编辑距离(困难)


    题目描述

    给你两个单词 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')

    做题思路

    - 定义dp数组

     dp[i][j]表示以下标i-1为结尾的字符串word1和以下标j-1为结尾的字符串word2的最近编辑距离。

    - 确定递推公式

    @ word1[i-1]==word2[j-1]时,不需要任何编辑,dp[i][j]=dp[i-1][j-1]

    @ word1[i-1]!=word2[j-1]时,可能会进行增、删、换的操作

            # word1删除一个元素:dp[i][j]=dp[i-1][j]+1

            # word2删除一个元素:dp[i][j]=dp[i][j-1]+1

            # 增加元素和删除元素属于同一种情况,即word2添加一个元素相当于word1删除一个元素

            # 替换元素:dp[i][j]=dp[i-1][j-1]+1

            # 由于寻找的是最近编辑距离,所以应为上述三者中的最小值

    - dp初始化

    dp[i][0]=i:以下标i-1为结尾的字符串word1和空字符串word2的最近距离,即相当于对word1里面的元素全部做删除操作;

    dp[0][j]=j同理。

    代码

    1. class Solution {
    2. public int minDistance(String word1, String word2) {
    3. int len1=word1.length();
    4. int len2=word2.length();
    5. //dp数组有效位从1开始
    6. int[][] dp=new int[len1+1][len2+1];
    7. //初始化
    8. for(int i=1;i<=len1;i++){
    9. dp[i][0]=i;
    10. }
    11. for(int j=1;j<=len2;j++){
    12. dp[0][j]=j;
    13. }
    14. for(int i=1;i<=len1;i++){
    15. for(int j=1;j<=len2;j++){
    16. if(word1.charAt(i-1)==word2.charAt(j-1)){
    17. dp[i][j]=dp[i-1][j-1];
    18. }else{
    19. dp[i][j]=Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1]))+1;
    20. }
    21. }
    22. }
    23. return dp[len1][len2];
    24. }
    25. }

  • 相关阅读:
    OpenHarmony docker环境搭建所见的问题和解决
    单链表的方向翻转,为什么程序逻辑是这样的?
    【Redis】Jedis
    项目管理工具的功能与帮助一览
    折半插入排序算法
    如何在Firewalld中为特定IP地址开放端口
    金融业信贷风控算法2-初等统计理论
    STM32 + RTThread + UGUI
    Dubbo详解,用心看这一篇文章就够了【重点】
    jvm实践
  • 原文地址:https://blog.csdn.net/zxw20171828/article/details/125407421