首页 > 其他 > 详细

LeetCode Edit Distance

时间:2015-04-04 16:45:29      阅读:228      评论: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

题意:求两个字符串的最小编辑距离,就是最少的操作(改,增,删)使得两个字符串相同。

思路:典型的DP,设dp[i][j]表示第一个字符串的前i个(1-i)和第二个字符串的前j个(1-j)的最小编辑距离。那么如果第i个和第j个相同的话,那么

dp[i][j]=dp[i-1][j-1],否则可以替换一下也就是dp[i][j]=dp[i-1][j-1]+1,其他的操作就是增和删,那么就可以取dp[i-1][j]+1、dp[i][j-1]+1、之前的较小值。

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.length() + 1;
        int len2 = word2.length() + 1;
        vector<vector<int> > f(len1, vector<int>(len2));

        for (int i = 0; i < len1; i++) f[i][0] = i;
        for (int i = 0; i < len2; i++) f[0][i] = i;

        for (int i = 1; i < len1; i++)
            for (int j = 1; j < len2; j++) {
                if (word1[i-1] == word2[j-1]) 
                    f[i][j] = f[i-1][j-1];
                else f[i][j] = f[i-1][j-1] + 1;
                f[i][j] = min(f[i][j], min(f[i-1][j]+1, f[i][j-1]+1));
            }

        return f[len1-1][len2-1];
    }
};


LeetCode Edit Distance

原文:http://blog.csdn.net/u011345136/article/details/44873657

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