首页 > 其他 > 详细

Edit Distance

时间:2014-03-29 06:11:15      阅读:400      评论:0      收藏:0      [点我收藏+]

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


这个算法过程就不用说了,值得提一下的就是空间效率。 这个实现只用了min(len1, len2)的额外空间,在不需要重构编辑过程的情况下(指需要知道distance),空间效率算是最优的了。

实际产品中可以再考虑掐头去尾之类的预处理减少两端完全相同部分的计算, 这么做是否值得看实际的应用场合。



class Solution {
public:
    int minDistance(string &word1, string &word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        if (len1 > len2) return minDistance(word2, word1);
        if (len1 == 0 || len2 == 0) return len1 == 0 ? len2 : len1;
        
        vector<int> ret(len1 + 1, 0);
        for (int i = 1; i <= len1; i++) {
            ret[i] = i;    
        }
        
        for (int i = 1; i <= len2; i++) {
            int pre = i, cur = 0;
            for (int j = 1; j <= len1; j++) {
                if (word1[j - 1] == word2[i - 1]) {
                    cur = ret[j - 1];
                } else {
                    cur = min(pre, min(ret[j], ret[j - 1])) + 1;
                }
                
                ret[j - 1] = pre;
                pre = cur;
            }
            
            ret[len1] = pre;
        }
        
        return ret[len1];
    }
};


Edit Distance,布布扣,bubuko.com

Edit Distance

原文:http://blog.csdn.net/icomputational/article/details/22439609

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!