首页 > 其他 > 详细

leetcode第一刷_Edit Distance

时间:2014-05-11 04:55:04      阅读:408      评论:0      收藏:0      [点我收藏+]

最小编辑距离,很经典的问题,今年微软实习生的笔试有一个这个的扩展版,牵扯到模板之类的,当时一行代码也没写出来。。

dp可以很优雅的解决这个问题,状态转移方程也很明确。用pos[i][j]表示word1的前i个字符与word2的前j个字符之间的编辑距离。如果word[i-1]与word[j-1]相等,那pos[i][j]与pos[i-1][j-1]相等,否则的话,根据编辑的几种操作,可以从三种情况中选取代价最小的一种,从word1中删除一个字符?从word2中删除一个字符?修改其中一个?边界也很简单,一个字符串长度为0时,编辑距离一定是根据另一个的长度不断增加的。

写成代码一目了然:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.length(), len2 = word2.length();
        int pos[len1+1][len2+1];
        for(int i=0;i<=len1;i++)
            pos[i][0] = i;
        for(int i=0;i<=len2;i++)
            pos[0][i] = i;
        for(int i=1;i<=len1;i++){
            for(int j=1;j<=len2;j++){
                if(word1[i-1] == word2[j-1])
                    pos[i][j] = pos[i-1][j-1];
                else{
                    pos[i][j] = min(pos[i-1][j], min(pos[i-1][j-1], pos[i][j-1]))+1;
                }
            }
        }
        return pos[len1][len2];
    }
};


leetcode第一刷_Edit Distance,布布扣,bubuko.com

leetcode第一刷_Edit Distance

原文:http://blog.csdn.net/u012792219/article/details/25498201

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