第十周:[leetCode] 72. Edit Distance

题目:链接

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

为加强利用动态规划解题的思维,我时不时会选择一道动态规划的题目进行学习,在写之前搜到一篇解析很详细且清楚的文章,那我就以简单明了的方式说明:

解题思路:
    新建二维数组,D[len1+1][len2+2]保存编辑距离的长度,其中D[i][j] 为 word1 的0-i位组成的子串和word2的0-j位组成的子串的编辑距离,则有:
(1) word1或word2其中一个长度为0,则编辑距离为另一字符串长度。
    D[i][0] = i;   
    D[0][j] = j;
(2)状态转移方程:
                  1. D[i-1][j] + 1;
    D[i][j] =     2. D[i][j-1] + 1;
                  3. D[i-1][j-1] + inc;   
 1 & 2. D[i-1][j]、D[i-1][j-1]进行增删换操作(即+1),可以得到 D[i][j]
 3. 如果word1第i位与word2第j位相等,不用进行增删换,inc为0,否则同上为1

c++解题:

    int minDistance(string word1, string word2) {
        int len1 = word1.size();
        int len2 = word2.size();
        int D[len1+1][len2+1];
        //设置初始状态
        for(int i = 0; i <= len2; i++)
            D[0][i] = i;
        for(int i = 0; i <= len1; i++)
            D[i][0] = i;
        for(int c = 1; c <= len2; c++){
            for(int r = 1; r <= len1; r++){
                int m = min(D[r-1][c], D[r][c-1]);
                //word2的第c位为word2[c-1],同word1,易错点
                int inc = word2[c-1] == word1[r-1]?0:1;
                D[r][c] = min(m + 1, D[r-1][c-1] + inc);
            }
        }
        return D[len1][len2];
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值