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)。

相关推荐
旖-旎3 小时前
《LeetCode 416 分割等和子集》
c++·算法·leetcode·动态规划·背包问题
晚笙coding1 天前
LeetCode 226. 翻转二叉树(Invert Binary Tree)
算法·leetcode·职场和发展
退休倒计时1 天前
【每日一题】LeetCode 287. 寻找重复数 TypeScript
算法·leetcode·typescript
G.O.G.O.G1 天前
《LeetCode SQL 从入门到精通(MySQL)》09
sql·mysql·leetcode
To_OC2 天前
LC 22 括号生成:刷完这道题,我终于搞懂回溯剪枝了
javascript·算法·leetcode
To_OC2 天前
LC 39 组合总和:回溯入门必刷题,我踩过的两个坑都在这了
javascript·算法·leetcode
兰令水2 天前
hot100【acm版】【2026.7.14打卡-java版本】
java·数据结构·算法·leetcode·面试
tachibana22 天前
hot100 课程表(207)
java·数据结构·算法·leetcode
旖-旎2 天前
《LeetCode 646 最长数对链 || LeetCode 1143 最长公共子序列》
c++·算法·leetcode·动态规划
Frostnova丶2 天前
(15)LeetCode 189. 轮转数组
数据结构·算法·leetcode