Edit Distance -- leetcode

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



  • 假如我们要将字符串str1变成str2
    sstr1(i)是str1的子串,范围[0到i),sstr1(0)是空串
    sstr2(j)是str2的子串,同上
    d(i,j)表示将sstr1(i)变成sstr2(j)的编辑距离

    首先d(0,t),0<=t<=str1.size()和d(k,0)是很显然的。
    当我们要计算d(i,j)时,即计算sstr1(i)到sstr2(j)之间的编辑距离,
    此时,设sstr1(i)形式是somestr1c;sstr2(i)形如somestr2d的话,
    将somestr1变成somestr2的编辑距离已知是d(i-1,j-1)
    将somestr1c变成somestr2的编辑距离已知是d(i,j-1)
    将somestr1变成somestr2d的编辑距离已知是d(i-1,j)
    那么利用这三个变量,就可以递推出d(i,j)了:
    如果c==d,显然编辑距离和d(i-1,j-1)是一样的
    如果c!=d,情况稍微复杂一点,

    1. 如果将c替换成d,编辑距离是somestr1变成somestr2的编辑距离 + 1,也就是d(i-1,j-1) + 1
    2. 如果在c后面添加一个字d,编辑距离就应该是somestr1c变成somestr2的编辑距离 + 1,也就是d(i,j-1) + 1
    3. 如果将c删除了,那就是要将somestr1编辑成somestr2d,距离就是d(i-1,j) + 1

      那最后只需要看着三种谁最小,就采用对应的编辑方案了。

上面对算法的分析来自于博客 uniEagle


在下面的实现代码中,我使用滚动数组,代替了二维数组。 而且只分配了一个数组。

另外,变量dist_i1_j1 表示 d(i-1, j-1)

                    dist_i_j      表示 d(i,j)

                    dist_i1_j    表示d(i-1, j)

                    dist_i_j1    表示d(i, j-1)


另外,下面代码中, 其实变量

dist_i1_j , <pre name="code" class="cpp">dist_i_j 

 

都是可以省掉的。

不过留着,可以更直观一点。


在leetcode上的实际执行时间为28ms。


class Solution {
public:
    int minDistance(string word1, string word2) {
        if (word1.size() < word2.size())
            word1.swap(word2);
            
        if (!word2.size()) return word1.size();
        
        vector<int> dist(word2.size());
        for (int j=0; j<dist.size(); j++) dist[j] = j+1;
        
        for (int i=0; i<word1.size(); i++) {
            int dist_i1_j1 = i;
            int dist_i_j1 = dist_i1_j1 +1;
            for (int j=0; j<word2.size(); j++) {
                const int dist_i1_j = dist[j];
                
                const int dist_i_j = word1[i] == word2[j] ? dist_i1_j1 : min(min(dist_i1_j1, dist_i1_j), dist_i_j1) + 1;
                
                dist_i_j1 = dist_i_j;
                dist_i1_j1 = dist[j];
                dist[j] = dist_i_j;
            }
        }
        
        return dist.back();
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值