Edit Distance(Dynamic Programming)

3 篇文章 0 订阅
1 篇文章 0 订阅

Edit Distance

Description

A problem on leetcode.

Definition

  • Given two strings word1 and word2
  • Do some operations to convert word1 to word2
  • Insert\delete\repalce 1 character is counted as one step
  • Find the minimum steps to complete this process
    For example:
    It will take 2 steps to convert abc to a by delete 2 times.

Analyse

  • We define D(i,j) : the minimun steps needed when we convert word1[i] to word2[j]
  • If we know the value of D(i1,j1),D(i,j1),D(i1,j) , then we can deduce the D(i,j) (it is easy to acquire)
    D(i,j)=minD(i1,j)+1D(i,j1) + 1D(i1,j1)+{01if word1[i] == word2[j]if word1[i] != word2[j]
  • We assume replace operation as one step, however, sometimes it maybe ruled as two steps. In that way, the branch of D(i1,j1) will be :

D(i1,j1)+{02if word1[i] == word2[j]if word1[i] != word2[j]

  • We got an example:
    • The table show the process to get D(9,9) where the word1 is INTENTION and the word2 is EXECUTION
    • The elements on the left edge or the bottom of the table can be acquired easily.
    • We can use recursion to obtain the full table.

image

Implement

  • From the Analyse , we can use a table to obtain the result. And the space costed is O(mn) .
  • In fact, by saving the last line, we can achieve the next line. The space costed will be decreased to O(n) or O(m) .
  • C++ code:
class Solution {
public:
    int minDistance(string word1, string word2) {
        int m(word1.size()),n(word2.size());
        vector<int> curCol(m+1,0);
        iota(curCol.begin(),curCol.end(),0);
        for(int i(1); i <= n; ++i)
        {
            int preCol = curCol[0];
            curCol[0] = i;
            for(int j(1); j <= m; ++j)
            {
                int buf = curCol[j];
                int add = (word1[j - 1]==word2[i - 1]) ? 0 : 1 ;
                curCol[j] = min( preCol + add, min( curCol[j] + 1, curCol[j - 1] + 1));
                preCol = buf;
            }
        }
        return curCol[m];

    }
};

Reference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值