72. 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
.
分析:
经典的DP问题。
1 public class Solution { 2 public int minDistance(String word1, String word2) { 3 int word2Length = word2.length(); 4 int word1Length = word1.length(); 5 6 int[][] distance = new int[word1Length + 1][word2Length + 1]; 7 8 for (int i = 0; i <= word1Length; i++) { 9 distance[i][0] = i; 10 } 11 12 for (int i = 0; i <= word2Length; i++) { 13 distance[0][i] = i; 14 } 15 16 for (int i = 1; i <= word1Length; i++) { 17 for (int j = 1; j <= word2Length; j++) { 18 if (word1.charAt(i - 1) == word2.charAt(j - 1)) { 19 distance[i][j] = distance[i-1][j-1]; 20 } else { 21 // delete add replace 22 distance[i][j] = Math.min(distance[i-1][j], Math.min(distance[i][j-1], distance[i-1][j-1])) + 1; 23 } 24 } 25 } 26 return distance[word1Length][word2Length]; 27 } 28 }