[leetcode]Edit Distance

动态规划,此题思考许久,出错不少。动态规划的转移方程倒是想出来了,转移方程的讨论可见: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/

但是对于i==0和j==0时的计算,以至于a和aa,以及a和ba这样的例子都计算错过。

后来看到一个用长度而非坐标来作为数组索引的,就更简单了:http://www.cnblogs.com/remlostime/archive/2012/11/06/2757668.html

public class Solution {

    public int minDistance(String word1, String word2) {

        // Start typing your Java solution below

        // DO NOT write main() function

        int len1 = word1.length();

        int len2 = word2.length();

        if (len1 == 0) return len2;

        if (len2 == 0) return len1;

        int m[][] = new int[len1][len2];

        

        m[0][0] = word1.charAt(0) == word2.charAt(0) ? 0 : 1;

        for (int j = 1; j < len2; j++) {

            if (word1.charAt(0) == word2.charAt(j)) {

                m[0][j] = j;

            }

            else {

                m[0][j] = m[0][j-1]+1;

            }

        }

        

        for (int i = 1; i < len1; i++) {

            if (word1.charAt(i) == word2.charAt(0)) {

                m[i][0] = i;

            }

            else {

                m[i][0] = m[i-1][0]+1;

            }

        }

        

        for (int i = 1; i < len1; i++) {

            for (int j = 1; j < len2; j++) {

                int x1 = m[i-1][j] + 1;

                int x2 = m[i][j-1] + 1;

                int x3 =  m[i-1][j-1];

                if (word1.charAt(i) != word2.charAt(j)) x3++;

                m[i][j] = Math.min(x1, Math.min(x2, x3));               

            }

        }

        return m[len1-1][len2-1];

    }

}

  

你可能感兴趣的:(LeetCode)