72.Edit Distance---dp

題目連接:https://leetcode.com/problems/edit-distance/description/數組

題目大意:找出兩個字符串之間的編輯距離(每次變化都只消耗一步)。ide

法一(借鑑):經典dp。代碼以下(耗時15ms):spa

 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     }
View Code

 dp數組變化(例子:abc到acde的編輯距離):code

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]中。blog

dp數組填充順序:從左上到右下,即每一次數值計算都要用到左邊,上邊,左上的數據。ip

相關文章
相關標籤/搜索