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

[LintCode] Edit Distance

时间:2015-11-11 06:29:00      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

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:

  • Insert a character
  • Delete a character
  • Replace a character

Example

Given word1 = "mart" and word2 = "karma", return 3.

 

SOLUTION :

先看问题,minimum number of steps,可以说基本就是DP问题了。

状态:由于是两个字符串,要分别用两个字符串的信息,所以二维DP,f(x,y) = w1前x位 变成 w2的前y位,需要多少步。

方程:情况1:w1的第i位跟w2的第j位相等,那么f(i,j) = f(i - 1, j - 1)

         情况2: 不想等:1,insert ,insert后,w2的j位被匹配,然后其他需要匹配的就是w1的前i个以及w2的前j - 1个。 f(i, j ) = f (i, j - 1) + 1

                              2, del, 删除后,需要匹配的就是w1前i-1位跟w2的前j位。 f(i, j) = f(i - 1, j) + 1

                              3,replace, 换了这个之后,相当于直接匹配这两个位置的字母,需要匹配剩下,i - 1,j -1个。f(i, j) = f (i - 1,j - 1) + 1

   总的方程就是:if(w1(i) == w2(j)) ==> f(i-1,j -1)

          else ==> min(insert,del, replace)

初始化:值得注意的是这里,f(i, 0) = i 以及 f(0, i) = i 意思就是w1或者w2为空时候的情况。

结果:f(w1.len,w2.len)

代码:

技术分享
public class Solution {
    /**
     * @param word1 & word2: Two string.
     * @return: The minimum number of steps.
     */
    // insert  f(i, j -1) + 1
    // del     f(i -1, j) + 1
    // replace f(i - 1, j - 1) + 1
    // word1(i) = word2(j) f(i - 1, j - 1);
    // f(0, 0) = 0;
    public int minDistance(String word1, String word2) {
        if (word1.length() == 0 || word1 == null){
            return word2.length();
        }
        if (word2.length() == 0 || word2 == null){
            return word1.length();
        }
        int[][] result = new int[word1.length() + 1][word2.length() + 1];
        for (int i = 0; i <= word1.length(); i++){
            result[i][0] = i;
        }
        for (int i = 0; i<= word2.length(); i ++){
            result[0][i] = i;
        }
        for (int i = 1; i <= word1.length(); i++){
            for (int j = 1; j <= word2.length(); j++){
                if (word1.charAt(i - 1) == word2.charAt(j - 1)){
                    result[i][j] = result[i - 1][j - 1];
                } else {
                    result[i][j] = Math.min(result[i - 1][j - 1], Math.min(result[i - 1][j], result[i][j - 1])) + 1;
                }
            }
        }
        return result[word1.length()][word2.length()];
    }
}
View Code

 

[LintCode] Edit Distance

标签:

原文地址:http://www.cnblogs.com/tritritri/p/4955100.html

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