LintCode Edit Distance

LintCode 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

For this problem, the dynamic programming is used.

Firstly, define the state MD(i,j) stand for the int number of minimum distance of changing i-char length word to j-char length word. MD(i, j) is the result of editing word1 which has i number of chars to word2 which has j number of word.

Second, we want to see the relationship between MD(i,j) with MD(i-1, j-1) ,  MD(i-1, j) and MD(i, j-1).

Thirdly, initilize all the base case as MD(i, 0) = i, namely that delete all i-char-long word to zero and MD(0, i) = i, namely insert zero length word to i-char-long word.

Fourth, solution is to calculate MD(word1.length(), word2.length())

 

 1 public class Solution {
 2     /**
 3      * @param word1 & word2: Two string.
 4      * @return: The minimum number of steps.
 5      */
 6     public int minDistance(String word1, String word2) {
 7         int n = word1.length();
 8         int m = word2.length();
 9         int[][] MD = new int[n+1][m+1];
10         
11         for (int i = 0; i < n+1; i++) {
12             MD[i][0] = i; 
13         }
14         
15         for (int i = 0; i < m+1; i++) {
16             MD[0][i] = i;
17         }
18         
19         for (int i = 1; i < n+1; i++) {
20             for (int j = 1; j < m+1; j++) {
21                 //word1's ith element is equals to word2's jth element
22                 if(word1.charAt(i-1) == word2.charAt(j-1)) {
23                     MD[i][j] = MD[i-1][j-1];
24                 }
25                 else {
26                     MD[i][j] = Math.min(MD[i-1][j-1] + 1,Math.min(MD[i][j-1] + 1, MD[i-1][j] + 1));
27                 }
28             }
29         }
30         return MD[n][m];
31     }
32 }

 

posted on 2016-08-15 10:31  猛犸猴子  阅读(110)  评论(0)    收藏  举报

导航