[leetcode] Edit Distance


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

tag: array, dynamic programming

教科书上着重介绍的内容,不不废话了。还是简单说下,这篇文章可能也会被初学者看到。

动态规划的基本思想,是从简单的初始条件出发,通过一些转移规则而逐渐解出复杂的情况。

这个问题里,我们需要维护一个编辑距离矩阵,里面记录着word1和word2的所有子串的编辑距离,包括本身。

需要注意的是,当word1[i] == word2[j]时,map[i][j] = map[i-1][j-1]。而不是map[i][j] = min (map[i-1][j-1], map[i-1][j], map[i][j-1])。一开始这里记错了。以及,注意处理空字符串。

C++:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int length = word1.length() + 1;
        int height = word2.length() + 1;
        int map[height][length];
        
        //handle empty string
        if (word1.empty()){
            return word2.length();
        }
        else if (word2.empty()){
            return word1.length();
        }
        
        //initialize edit distance matrix
        for (int i = 0; i < length; i++){
            map[0][i] = i;
        }
        for(int i = 0; i < height; i++){
            map[i][0] = i;
        }
        
        for(int i = 1; i < length; i++){
            for(int j = 1; j < height; j++){
                //same character
                if (word1[i-1] == word2[j-1]){
                    map[j][i] = map[j-1][i-1];
                }
                else{
                    map[j][i] = min(map[j-1][i-1], min(map[j-1][i], map[j][i-1])) + 1;
                }
            }
        }
        return map[height-1][length-1];
    }
};

Selection_007

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.