算法练习9:leetcode习题72. Edit Distance

本文介绍了如何解决LeetCode上的72题——编辑距离。编辑距离是指将一个字符串转换成另一个字符串所需的最少操作次数,包括插入、删除和替换字符。通过动态规划的方法,分析了问题的子结构并给出状态转移方程。最后,展示了C++代码实现。

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

题目

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:

  1. Insert a character
  2. Delete a character
  3. 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’)

算法思路

本周继续学习动态规划的问题,本题是动态规划里面的经典问题——编辑距离。
两个字符串的编辑距离指的是将两个字符串上下排列时,其字母不同的列数的最小值。它的一种实际意义就是题目上面的表述,将一个字符串变为另一个字符串所要进行的最小操作数,合法操作有插入、删除、替换。
我们拆解最后一位字符可能的情况
分解子问题的状态方程
dis[i][j] =min{1+dis[i-1][j], 1+dis[i][j-1], diff(i,j)+dis[i-1][j-1]}
dis[i][j]表示word1的前i个字符与word2的前j个字符的编辑距离
如果word1[i]==word2[j], diff(i,j)=0,否则diff(i,j)=1.

C++代码

class Solution {
public:
    int minDistance(string word1, string word2) {
		int dis[word1.size()+1][word2.size()+1];

        for (int i = 0; i <= word2.size(); ++i)
        {
            dis[0][i] = i;
        }

        for (int i = 1; i <= word1.size(); ++i)
        {
            dis[i][0] = i;
        }

        for (int i = 1; i <= word1.size(); ++i)
        {
            for (int j = 1; j <= word2.size(); ++j)
            {
                int temp = dis[i-1][j] < dis[i][j-1]?dis[i-1][j]:dis[i][j-1];
                temp++;
                int diff = 1;
                if (word1[i-1] == word2[j-1])
                {
                    diff = 0;
                }
                if (diff + dis[i-1][j-1] < temp)
                {
                    temp = diff + dis[i-1][j-1];
                }
                dis[i][j] = temp;
            }
        }

        return dis[word1.size()][word2.size()];

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值