LeetCode 之 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

这个题跟LCS基本一样,我这里有个函数的名字也叫LCS。。。。。于是乎,动态规划之。。。

这个题的思路如下:

1 a[indexA]==b[indexB] 那么返回LCS(a,b,indexA+1,indexB+1,record),即indexA和indexB都向后移1位,默认a[indexA]和b[indexB]就是一个确定的元素,我原来有这么一个疑惑,比如apqabcdefg 和 abcdefg 那么字符串a和b的第一个元素都是a啊,这个很明显,其实把a的apg都删除了,就和b一样了;但是我们上述的方法是把字符串a的第一个a和字符串b的第一个元素认为是一样的了啊。。。。。其实这是一样的,因为都要删除一次a,这个a出现的顺序没什么影响(KEY).如图1


图 1

2 如果不等呢。。。。。 good这么几种情况,我这里是从a变化到b:

   1)把a的第indexA个元素变成跟b的indexB的一样的元素,如图2:


图2

  2)把a的第indexA个元素删除,如图3


图3

 3)在a的第indexA个元素的位置插入b的第indexB的元素,如图4:


图4

很好,从上述的几种情况中找出最小的数字那个就是字符串a和字符串b的从indexA和indexB开始的转换所需的步数

然后。。。。循环!!!!


代码如下(248ms):

class Solution {
public:
    int minDistance(string word1, string word2) {
        vector<int> hor(word2.length()+1,-1);
        vector<vector<int>> record(word1.length()+1,hor);
        return LCS(word1,word2,0,0,record);
    }
    int LCS(string a , string b , int indexA , int indexB , vector<vector<int>> & record){
        if(indexA>=a.length()||indexB>=b.length()){
           int step = (a.size()-indexA) - (b.size()-indexB);
           step = step>0?step:0-step;
           record[indexA][indexB]= step;
           return step;
       }
       if(record[indexA][indexB]!=-1) return record[indexA][indexB];
       if(a[indexA]==b[indexB]){ 
           record[indexA][indexB] = LCS(a,b,indexA+1,indexB+1,record);
           return LCS(a,b,indexA+1,indexB+1,record);
        }
       //return min(LCS(a,b,indexA,indexB+1,record)+1 , LCS(a,b,indexA+1,indexB,record)+1 , LCS(a,b,indexA+1,indexB+1)+1 );
       record[indexA][indexB] = minNum( LCS(a,b,indexA,indexB+1,record)+1 , LCS(a,b,indexA+1,indexB,record)+1 , LCS(a,b,indexA+1,indexB+1,record)+1 );
       return record[indexA][indexB];
    }
    
    int minNum(int a, int b, int c){
        return min(min(a,b),c);
        
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值