[leetcode] 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

https://oj.leetcode.com/problems/edit-distance/

 

分析:编辑距离,算法导论课后题,编程之美上好像都有。概念的话,看 这里

思路1:dfs,复杂度指数级别,目测要超时。

public int minDistanceWithRecurse(String word1, String word2) {  
    if(word1.length() == 0){  
        return word2.length();  
    }  
    if(word2.length() == 0){  
        return word1.length();  
    }  
    if(word1.charAt(0) == word2.charAt(0)){  
        return minDistance(word1.substring(1), word2.substring(1));  
    }else{  
        int t1 = minDistance(word1.substring(1), word2);  
        int t2 = minDistance(word1, word2.substring(1));  
        int t3 = minDistance(word1.substring(1), word2.substring(1));  
        return Math.min(t1, Math.min(t2, t3)) + 1;  
    }  
}  

  

思路2: 二维的DP,详见参考1,分析的很好。

public class Solution {
    public int minDistance(String word1, String word2) {
        int length1 = word1.length();
        int length2 = word2.length();
        if (length1 == 0 || length2 == 0) {
            return length1 == 0 ? length2 : length1;
        }
        int[][] distance = new int[length1 + 1][length2 + 1];
        distance[0][0] = 0;
        for (int i = 1; i <= length1; i++) {
            distance[i][0] = i;
        }
        for (int i = 1; i <= length2; i++) {
            distance[0][i] = i;
        }
        for (int i = 1; i <= length1; i++) {
            for (int j = 1; j <= length2; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    distance[i][j] = distance[i - 1][j - 1];
                } else {
                    distance[i][j] = Math.min(distance[i - 1][j - 1], Math.min(distance[i][j - 1], distance[i - 1][j])) + 1;
                }
            }
        }
        return distance[length1][length2];
    }

    public static void main(String[] args) {
        System.out.println(new Solution().minDistance("eeba", "abca"));
    }

}
View Code

 

 

参考:

http://huntfor.iteye.com/blog/2077940

 

http://blog.unieagle.net/2012/09/19/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Aedit-distance%EF%BC%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%8B%E9%97%B4%E7%9A%84%E7%BC%96%E8%BE%91%E8%B7%9D%E7%A6%BB%EF%BC%8C%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/

posted @ 2014-06-27 22:26  jdflyfly  阅读(209)  评论(0编辑  收藏  举报