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())

 public class Solution {
/**
* @param word1 & word2: Two string.
* @return: The minimum number of steps.
*/
public int minDistance(String word1, String word2) {
int n = word1.length();
int m = word2.length();
int[][] MD = new int[n+][m+]; for (int i = ; i < n+; i++) {
MD[i][] = i;
} for (int i = ; i < m+; i++) {
MD[][i] = i;
} for (int i = ; i < n+; i++) {
for (int j = ; j < m+; j++) {
//word1's ith element is equals to word2's jth element
if(word1.charAt(i-) == word2.charAt(j-)) {
MD[i][j] = MD[i-][j-];
}
else {
MD[i][j] = Math.min(MD[i-][j-] + ,Math.min(MD[i][j-] + , MD[i-][j] + ));
}
}
}
return MD[n][m];
}
}
上一篇:app后端设计(7)-- 项目管理


下一篇:Apache Tomcat Nginx的区别和联系