'LeetCode算法第72題:編輯距離'

算法 Java 小天使淘淘 2019-09-07
"

問題描述

給定兩個單詞 word1 和 word2,計算出將 word1 轉換成 word2 所使用的最少操作數 。

你可以對一個單詞進行如下三種操作:

插入一個字符

刪除一個字符

替換一個字符

示例 1:

輸入: word1 = "horse", word2 = "ros"
輸出: 3
解釋:
horse -> rorse (將 'h' 替換為 'r')
rorse -> rose (刪除 'r')
rose -> ros (刪除 'e')

示例 2:

輸入: word1 = "intention", word2 = "execution"
輸出: 5
解釋:
intention -> inention (刪除 't')
inention -> enention (將 'i' 替換為 'e')
enention -> exention (將 'n' 替換為 'x')
exention -> exection (將 'n' 替換為 'c')
exection -> execution (插入 'u')

思路:

這道題目可以使用動態規劃來實現,通過定義一個int類型的二維數組dp,使得dp[i][j] 表示將單詞word1 中的前 i 個字符 轉換成 word2 中前j個字符所需的最少操作數。在用workd1 中第i個字符和word2中第j個字符對比過程中,會存在如下幾種情況:

1、workd1 中第i個字符和word2中第j個字符相同,此時 dp[i][j] = dp[i][j-1]

2、workd1 中第i個字符和word2中第j個字符不相同,此時 可以通過插入、刪除、替換三種操作來獲取最少的一個操作數,這三種情況如下:

2.1、插入 dp[i][j] = dp[i][j-1] + 1

2.2、刪除 dp[i][j] = dp[i-1][j] + 1

2.3、替換 dp[i][j] = dp[i-1][j-1] + 1

java代碼:

public int minDistance(String word1, String word2) {
int[][] dp = new int[word1.length() + 1][word2.length() + 1];
dp[0][0] = 0;

for(int i = 1; i < dp[0].length; i ++){
dp[0][i] = dp[0][i - 1] + 1;
}

for(int i = 1; i < dp.length; i ++){
dp[i][0] = dp[i - 1][0] + 1;
}

for(int i = 1; i < dp.length; i ++){
for(int j = 1; j < dp[0].length; j ++){
if(word1.charAt(i-1) == word2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = Math.min(Math.min(dp[i][j-1],dp[i-1][j]),dp[i-1][j-1]) + 1;
}
}
}

return dp[word1.length()][word2.length()];
}
"

相關推薦

推薦中...