1. 程式人生 > >[leetcode72]Edit Distance

[leetcode72]Edit Distance

imu pub 刪除 scrip minimum eps ace insert 二維

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

/*和712題Minimum ASCII Delete Sum for Two Strings基本一模一樣,都是調整兩個字符串到相等,一看不需要過程只要步數,就是動態規劃
    從兩個字符串的開頭開始比較,一個一個比較,我們用二維數組dp[i][j]代表字符串1前i個字符和字符串2前j個字符調整到相同時,str1所需要調整的步數
       有三種方法可以到達dp[i][j]:
       1.dp[i-1][j] + 1:由於從dp[i-1][j]到dp[i][j]是多考慮了str1的一個字符,但是str2字符數沒變,所以要想相同,必須刪除str[i],步驟+1
       2.dp[i][j-1] + 1:對應於1,這個是多考慮str2的一個字符,所以str1應該添加上,步驟+1
       3.dp[i-1][j-1] + a,這裏是考慮兩個str都加了一個,所以str1[i] =str2[j]時,a=0;str1[i] !=str2[j]時,str1[i]應該改成str2[j],a=1
       這三種情況每次比較出最小的來,最後返回dp[str1.length][str2.length](這裏字符串下標從1開始,因為我們考慮dp數組的第0行代表str1還啥也沒有,第0列代表str2啥也沒有)
     
*/ public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[][] dp = new int[m+1][n+1]; //初始化動態數組,就是第0行數據和第1行數據,註意由於下標從1開始,所以charAt的時候要-1 for (int i = 1;i < m+1;i++) dp[i][0] = dp[i-1][0] + 1;
for (int i = 1;i < n+1;i++) dp[0][i] = dp[0][i-1] + 1; for (int i = 1;i < m+1;i++) { for (int j = 1;j < n+1;j++) { //先看word1[i]和word2[j]是不是相等,確定a int a =(word1.charAt(i-1) == word2.charAt(j-1))? 0 : 1;
//比較三種情況 dp[i][j] = Math.min(dp[i-1][j-1]+a,Math.min(dp[i-1][j] + 1,dp[i][j-1] + 1)); } } return dp[m][n];

[leetcode72]Edit Distance