(Leetcode)72. Edit Distance(hard)

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character

这个就和上课讲到的比较字符串的问题是一样的,书上也有提到,方法就是从右端开始考虑(相当于考虑前缀),分三种情况,对齐(包括匹配与不匹配),第一个字符串为空(insert和delete都相当于空了一个位置),第二个字符为空,比较前缀在这些情况下的最小值,这样就能得到动态规划中的子问题,用E(m,n)来表示第一个string前m位和第二个string前n位的差别数,当m和n分别为字符长度时即为所求,于是得到关系式为:
E(m,n)=min{1+E(m-1,n),1+E(m,n-1),dif(m,n)+E(m-1,n-1)},用二维数组储存答案,即可得到所求。
我的代码:

#include<cmath>
#include<algorithm>
#include<cstdlib>
class Solution {
public:
    int minDistance(string word1, string word2) {
        int outcome[1000][1000] = {};
        for (int i = 0; i <= word1.size(); i++) {
            outcome[0][i] = i;
        }
        for (int i = 0; i <= word2.size(); i++) {
            outcome[i][0] = i;
        }
        for (int i = 1; i <= word2.size(); i++) {
            for (int j = 1; j <= word1.size(); j++) {
                int s = 1;
                if (word1[j-1] == word2[i-1])
                    s = 0;
                int mins = 1 + outcome[i - 1][j];
                if (mins > 1 + outcome[i][j - 1]) {
                    mins = 1 + outcome[i][j - 1];
                }
                if (mins > s + outcome[i - 1][j - 1]) {
                    mins = s + outcome[i - 1][j - 1];
                }
                outcome[i][j] = mins;
            }
        }
        return outcome[word2.size()][word1.size()];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值