美文网首页
[leetcode]72. 编辑距离

[leetcode]72. 编辑距离

作者: 祁晏晏 | 来源:发表于2020-09-05 15:36 被阅读0次

题目

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

关键词

动态规划

经典题目

解题

https://labuladong.gitbook.io/algo/dong-tai-gui-hua-xi-lie/bian-ji-ju-li

这个链接里有动图,在想不明白的时候可以加深理解。

感觉也没啥好说的,三步走,确定定义,确定base case,确定状态转移方程.

本题难点还是在状态转移方程上

if word1[i-1] != word2[j-1]: dp[i][j] = min (dp[i-1][j-1] + 1, dp[i][j-1] + 1, dp[i-1][j] + 1); else: dp[i][j] = dp[i-1][j-1]

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.size(), len2 = word2.size();
        vector<vector<int> > dp(len1+1, vector<int>(len2+1, 0));
        //base case
        for(int i = 0; i <= len1; i++){
            dp[i][0] = i;
        }
        for(int j = 0; j <= len2; j++){
            dp[0][j] = j;
        }

        //状态转移
        /*
        if word1[i-1] != word2[j-1]:
        dp[i][j] = min (dp[i-1][j-1] + 1, dp[i][j-1] + 1, dp[i-1][j] + 1);
        else:
        dp[i][j] = dp[i-1][j-1]
        */
        for (int i = 1; i <= len1; i++){
            for (int j = 1; j <= len2; j++){
                if (word1[i-1] == word2[j-1])
                    dp[i][j] = dp[i-1][j-1];
                else{
                    dp[i][j] = min(min(dp[i-1][j-1] + 1, dp[i][j-1] + 1), dp[i-1][j] + 1);
                }
            }
        }
        return dp[len1][len2];
    }
};

总结和教训

经典题目,希望理解并牢牢记住

相关文章

  • 72.编辑距离

    72. 编辑距离[https://leetcode-cn.com/problems/edit-distance/]...

  • 编辑距离(edit distance)

    编辑距离 LeetCode 72. 编辑距离 概念 编辑距离,是指将字符串word1通过替换、删除、增加字符的操作...

  • 72.编辑距离

    72.编辑距离[https://leetcode.cn/problems/edit-distance/] 给你两个...

  • [leetcode]72. 编辑距离

    题目 链接:https://leetcode-cn.com/problems/edit-distance/ 给你两...

  • leetcode 72.编辑距离

    编辑距离可以说是动态规划算法中经典的、知名的题目了,题目难度也不小,是一道很好的动态规划的题目。很可能会出现在面试...

  • LeetCode 72. 编辑距离

    1、题目 2、分析 这个题目,主要是抽象起来比较难,其实解法还是挺经典的。1、用自上而下的递归法,主要重叠子的问题...

  • LeetCode 72. 编辑距离

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

  • 经典动态规划:编辑距离

    读完本文,你可以去力扣拿下如下题目: 72.编辑距离[https://leetcode-cn.com/proble...

  • python实现leetcode之72. 编辑距离

    解题思路 经典的动态规划问题最优子结构对应三种操作 72. 编辑距离[https://leetcode-cn.co...

  • 72. Edit Distance, 编辑距离

    72. Edit Distance, 编辑距离

网友评论

      本文标题:[leetcode]72. 编辑距离

      本文链接:https://www.haomeiwen.com/subject/avkfektx.html