72. 编辑距离

文章目录

题目

多维动态规划:72. 编辑距离

给你两个单词 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 由小写英文字母组成

代码

cpp 复制代码
class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1=word1.length();
        int len2=word2.length();
        vector<vector<int>>dp(len1+1,vector<int>(len2+1,0));
        for(int i=1;i<=len2;++i){
            dp[0][i]=dp[0][i-1]+1;
            }
        for(int i=1;i<=len1;++i){
            dp[i][0]=dp[i-1][0]+1;
            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],dp[i-1][j]),dp[i][j-1])+1;
                }
            }
        }
        return dp.back().back();   
        }
};

原理图

原理解释

提示:算法流程及解释在代码中已标注

该算法使用动态规划求解两个字符串的编辑距离问题。

dpij 表示 word1 前 i 个字符转换为 word2 前 j 个字符所需的最少操作次数。

动态规划数组大小为 (len1+1) × (len2+1)。

dp0i 表示空字符串转换为 word2 前 i 个字符需要连续插入 i 次。

dpi0 表示 word1 前 i 个字符转换为空字符串需要连续删除 i 次。

外层循环遍历 word1 的每一个字符。

内层循环遍历 word2 的每一个字符。

当 word1i-1 == word2j-1 时,当前位置无需额外操作。

字符相等时状态转移为 dpij = dpi-1j-1。

当两个字符不相等时,需要考虑替换、删除和插入三种操作。

dpi-1j-1 + 1 表示执行一次替换操作。

dpi-1j + 1 表示删除 word1 当前字符。

dpij-1 + 1 表示向 word1 中插入一个字符。

状态转移取三种操作中的最小值再加 1。

最终答案保存在 dplen1len2 中。

该算法的时间复杂度为 O(len1 × len2)。

该算法的空间复杂度为 O(len1 × len2)。

相关推荐
Navigator_Z17 分钟前
LeetCode //C - 1283. Find the Smallest Divisor Given a Threshold
c语言·算法·leetcode
我不会起名字3221 小时前
二叉树的遍历与二叉搜索树:把递归、迭代、还原树一次讲透
数据结构·leetcode·二叉树·二叉搜索树
yi0112 小时前
Leetcode 49 用 “身份证‘‘巧解
人工智能·笔记·python·算法·leetcode·哈希表
yi0112 小时前
DAY22: LeetCode 733:图像渲染——从二维网格开始理解 DFS 和 BFS
数据结构·笔记·python·算法·leetcode·深度优先·宽度优先
Pniubi2 小时前
力扣41缺失的第一个正数(哈希表法)
算法·leetcode·职场和发展
Nil2083 小时前
leetcode 70爬楼梯
算法·leetcode·动态规划
longlongzihan5 小时前
LeetCode 189. 轮转数组:从直观模拟到最优原地算法
c++·算法·leetcode
longlongzihan5 小时前
LeetCode 76. 最小覆盖子串:滑动窗口算法详解
算法·leetcode·滑动窗口
All for pursuit.16 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
夏幻灵1 天前
每日一题:LeetCode 3:无重复字符的最长子串——滑动窗口思路详解
算法·leetcode·职场和发展