标题: | Edit Distance |
通过率: | 26.1% |
难度: | 难 |
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
本题是动态规划的经典题目,公式如下:
1、s1.length==0,return s2.length;
2、s2.length==0,return s1.length;
3、if s1.charat(i)==s2.charat(j),res[i][j]=res[i-1][j-1]
else res[i][j]=min(res[i-1][j],res[i][j-1],res[i-1][i-1]+1)
具体看代码:
1 public class Solution { 2 public int minDistance(String word1, String word2) { 3 int len1 = word1.length(); 4 int len2 = word2.length(); 5 6 // len1+1, len2+1, because finally return dp[len1][len2] 7 int[][] dp = new int[len1 + 1][len2 + 1]; 8 9 for (int i = 0; i <= len1; i++) 10 dp[i][0] = i; 11 12 for (int j = 0; j <= len2; j++) 13 dp[0][j] = j; 14 15 16 //iterate though, and check last char 17 for (int i = 1; i <= len1; i++) { 18 char c1 = word1.charAt(i-1); 19 for (int j = 1; j <= len2; j++) { 20 char c2 = word2.charAt(j-1); 21 22 //if last two chars equal 23 if (c1 == c2) { 24 //update dp value for +1 length 25 dp[i][j] = dp[i-1][j-1]; 26 } else { 27 int replace = dp[i-1][j-1] + 1; 28 int insert = dp[i-1][j] + 1; 29 int delete = dp[i][j-1] + 1; 30 31 int min = Math.min(replace, insert); 32 min = Math.min(min,delete); 33 dp[i][j] = min; 34 } 35 } 36 } 37 38 return dp[len1][len2]; 39 } 40 }