Edit Distance(动态规划)

这篇博客详细介绍了如何使用动态规划解决Edit Distance问题,即找到将单词word1转换为word2所需的最小操作数,包括插入、删除和替换字符。通过分析和展示状态转移方程,阐述了从两个字符串的子问题逐步求解的过程,并提供了相关示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Edit Distance

题目

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

Insert a character
Delete a character
Replace a character
Example 1:

Input: word1 = “horse”, word2 = “ros”
Output: 3
Explanation:
horse -> rorse (replace ‘h’ with ‘r’)
rorse -> rose (remove ‘r’)
rose -> ros (remove ‘e’)
Example 2:

Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)

分析

用动态规划的思想去解决这个问题,那么意味着我们需要寻找这两个字符串的子问题的解,那么这个子问题怎么解决呢?
我们采用一个二维数组来表示count[i][j]表示字符串长为i和字符串长为j的字符的编辑距离,对于子问题,我们可以采用将i和j逐步缩小的策略,那么最终问题可以看作解决count[i][j],而每个字符串与空串的编辑距离是明显的,及count[0][j]和count[i][0]是明显知道的。
那么对于子问题可以有一下三种情况
在这里插入图片描述
最后可以知道状态转移方程为:
在这里插入图片描述
其中diff(i,j)是指当串1和串2的下标i和下标j对应的字符相等的时候为0,否则需要一步编辑距离,则为1.

源码

class Solution {
public:
    int minDistance(string word1, string word2) {
        int size1 = word1.size();
        int size2 = word2.size();
        vector<vector<int>> count(size1+1, vector<int>(size2+1, 0));
        for(int i = 0; i <= size1; i++) {
        	count[i][0] = i;
        }
        for(int i = 0; i <= size2; i++) {
        	count[0][i] = i;
        }

        for(int i = 1; i <= size1; i++) {
        	for(int j = 1; j <= size2; j++) {
        		int tag = 0;
        		if(word1[i-1] != word2[j-1]) {
        			tag = 1;
        		}
        		count[i][j] = min(count[i-1][j]+1, count[i][j-1]+1);
        		count[i][j] = min(count[i][j], tag+count[i-1][j-1]);
        	}
        }
        return count[size1][size2];
    }
};

觉得博主写的好
在这里插入图片描述

更多技术博客https://vilin.club/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值