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

相关推荐
To_OC2 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode
To_OC3 天前
LC 1 两数之和:面试第一道必考题,暴力解法直接被面试官 pass
javascript·算法·leetcode
想吃火锅10059 天前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
凌波粒9 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
退休倒计时9 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
小欣加油9 天前
leetcode3612 用特殊操作处理字符串I
数据结构·c++·算法·leetcode·职场和发展
凌波粒9 天前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode
凌波粒9 天前
LeetCode--46.全排列(回溯算法)
数据结构·算法·leetcode
吃着火锅x唱着歌9 天前
LeetCode 2530.执行K次操作后的最大分数
数据结构·算法·leetcode
sheeta19989 天前
LeetCode 每日一题笔记 日期:2026.06.16 题目:3612. 字符串特殊符号处理
笔记·算法·leetcode