码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode || 72、Edit Distance

时间:2015-04-09 10:36:31      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:leetcode   dp   string   算法   

problem:

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

Hide Tags
 Dynamic Programming String
题意:求将字符串word1 转换为word2 所需最小的步数,操作包括插入、替代和删除一个字符

thinking:

(1)求全局最优解,锁定DP法

(2)DP的状态转移公式不好找,有几点是DP法共有的,可以有点启发:1、DP大都借助数组实现递推操作 2、DP法的时间复杂度:一维为O(N),二维:O(M*N)

(3)

如果我们用 i 表示当前字符串 A 的下标,j 表示当前字符串 B 的下标。 如果我们用d[i, j] 来表示A[1, ... , i] B[1, ... , j] 之间的最少编辑操作数。那么我们会有以下发现:
1. d[0, j] = j;
2. d[i, 0] = i;
3. d[i, j] = d[i-1, j - 1] if A[i] == B[j]
4. d[i, j] = min(d[i-1, j - 1], d[i, j - 1], d[i-1, j]) + 1  if A[i] != B[j]  //分别代表替换、插入、删除

code:

class Solution {
public:
    int minDistance(string word1, string word2) {
        vector<vector<int> > f(word1.size()+1, vector<int>(word2.size()+1));
        
        f[0][0] = 0;
        for(int i = 1; i <= word2.size(); i++)
            f[0][i] = i;
        
        for(int i = 1; i <= word1.size(); i++)
            f[i][0] = i;
            
        for(int i = 1; i <= word1.size(); i++)
            for(int j = 1; j <= word2.size(); j++)
            {
                f[i][j] = INT_MAX;
                if (word1[i-1] == word2[j-1]) 
                    f[i][j] = f[i-1][j-1];
                
                f[i][j] = min(f[i][j], f[i-1][j-1] + 1); //replace
                f[i][j] = min(f[i][j], min(f[i-1][j], f[i][j-1]) + 1); //delete or insert               
            }
            
        return f[word1.size()][word2.size()];
    }
};


leetcode || 72、Edit Distance

标签:leetcode   dp   string   算法   

原文地址:http://blog.csdn.net/hustyangju/article/details/44955255

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!