72.Edit Distance---dp
题目链接:https://leetcode.com/problems/edit-distance/description/
题目大意:找出两个字符串之间的编辑距离(每次变化都只消耗一步)。
法一(借鉴):经典dp。代码如下(耗时15ms):
1 //dp公式:dp[i][j]表示第一个字符串前i个字符到第二个字符串前j个字符的编辑距离长度 2 //当word1[i]==word2[j]时,dp[i][j]=dp[i-1][j-1] 3 //否则,dp[i][j]=min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1 4 public int minDistance(String word1, String word2) { 5 int len1 = word1.length(), len2 = word2.length(); 6 int dp[][] = new int[len1+1][len2+1]; 7 //初始化 8 for(int i = 0; i <= len1; i++) { 9 dp[i][0] = i; 10 } 11 for(int i = 0; i <= len2; i++) { 12 dp[0][i] = i; 13 } 14 for(int i = 1; i <= len1; i++) {//下标从1开始 15 for(int j = 1; j <= len2; j++) { 16 if(word1.charAt(i - 1) == word2.charAt(j - 1)) { 17 dp[i][j] = dp[i - 1][j - 1]; 18 } 19 else { 20 int min = Integer.MAX_VALUE; 21 if(min > dp[i - 1][j - 1]) { 22 min = dp[i - 1][j - 1]; 23 } 24 if(min > dp[i][j - 1]) { 25 min = dp[i][j - 1]; 26 } 27 if(min > dp[i - 1][j]) { 28 min = dp[i - 1][j]; 29 } 30 dp[i][j] = min + 1; 31 } 32 } 33 } 34 return dp[len1][len2]; 35 }
dp数组变化(例子:abc到acde的编辑距离):
0 | 1("a") | 2("c") | 3("d") | 4("e") |
1("a") | 0(a->a) | 1(a->ac) | 2(a->acd) | 3(a->acde) |
2("b") | 1(ab->a) | 1(ab->ac) | 2(ab->acd) | 3(ab->acde) |
3("c") | 2(abc->a) | 1(abc->ac) | 2(abc->acd) | 3(abc->acde) |
从上表可清楚看见最后结果在dp[3][4]中。
dp数组填充顺序:从左上到右下,即每一次数值计算都要用到左边,上边,左上的数据。