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

 Leetcode:Edit Distance  解题报告

SOLUTION 1:

REF:
http://www.cnblogs.com/etcow/archive/2012/08/30/2662985.html
http://www.cnblogs.com/etcow/archive/2012/08/30/2662985.html
http://blog.csdn.net/fightforyourdream/article/details/13169573
http://www.cnblogs.com/TenosDoIt/p/3465316.html

相当经典的一道递归题目,而且难度级别为4.



例子: "ababd" -> "ccabab"

  先初始化matrix如下。意思是,比如"_" -> "cca" = 2 操作是插入'c','c','a',共3步。 "abab" -> "+ "_" 删除'a','b','a','b',共4 步。

  _ a b a b d
_ 0 1 2 3 4 5
c 1          
c 2          
a 3          
b 4          
a 5          
b 6          

  然后按照注释里的方法填满表格,返回最后一个数字(最佳解)

 

  _ a b a b d
_ 0 1 2 3 4 5
c 1 1 2 3 4 5
c 2 2 2 3 4 5
a 3 2 3 2 3 4
b 4 3 2 3 2 3
a 5 4 3 2 3 3
b 6 5 4 3 2 3
 1 public class Solution {
 2     public int minDistance(String word1, String word2) {
 3         if (word1 == null || word2 == null) {
 4             return 0;
 5         }
 6         
 7         int len1 = word1.length();
 8         int len2 = word2.length();
 9         
10         int[][] D = new int[len1 + 1][len2 + 1];
11         
12         for (int i = 0; i <= len1; i++) {
13             for (int j = 0; j <= len2; j++) {
14                 if (i == 0) {
15                     D[i][j] = j;
16                 } else if (j == 0) {
17                     D[i][j] = i;
18                 } else {
19                     if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
20                         D[i][j] = D[i - 1][j - 1];
21                     } else {
22                         D[i][j] = Math.min(D[i - 1][j - 1], D[i][j - 1]);
23                         D[i][j] = Math.min(D[i][j], D[i - 1][j]);
24                         D[i][j]++;
25                     }
26                 }
27             }
28         }
29         
30         return D[len1][len2];
31     }
32 }
View Code

相关文章: