LeetCode 72. Edit Distance

题目描述

出处 https://leetcode.com/problems/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:

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


分析

这道题的目的是求 word1 转变为 word2 的最少步骤,可以采用动态规划的方法。
对于两个字符串 word1[1…i] 与 word2[1…j] 的匹配,用 E(i,j) 代表现在的情况,其中最右侧的列只有三种情况: word1[i] 对应 空; word2[j] 对应 空;word1[i] 对应 word2[j];则可以将原问题变化为更小的三个子问题进行匹配,并取三个子问题中的最小者
则 E(i,j) = min{1+E(i-1,j), 1+E(i,j-1), diff(i,j)+E(i-1,j-1)} (当word1[i] == word2[j] 令diff(i,j) = 0 ,否则diff(i,j) = 1)


最终结果

class Solution {
public:
    int minDistance(string word1, string word2) {
        int E[word1.length()+1][word2.length()+1] = {0};
        for (int i = 0; i <= word1.length(); i++) {
            E[i][0] = i;
        }
        for (int j = 0; j <= word2.length(); j++) {
            E[0][j] = j;
        }
        for (int i = 1; i <= word1.length(); i++) {
            for (int j = 1; j <= word2.length(); j++) {
                int tem = 0;
                if (word1[i-1] != word2[j-1])
                    tem = 1;
                int min = 1 + E[i-1][j];
                int min2 = 1 + E[i][j-1];
                int min3 = tem + E[i-1][j-1];
                if (min > min2) 
                    min = min2;
                if (min > min3)
                    min = min3;
                
                E[i][j] = min;
            }
        }
        
        return E[word1.length()][word2.length()];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

妙BOOK言

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值