[Leetcode] Edit Distance 最小編輯距離

Edit Distance

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.)web

You have the following 3 operations permitted on a word:算法

a) Insert a character
b) Delete a character
c) Replace a characterui

動態規劃

複雜度

時間 O(NM) 空間 O(NM)code

思路

這是算法導論中經典的一道動態規劃的題。假設dp[i-1][j-1]表示一個長爲i-1的字符串str1變爲長爲j-1的字符串str2的最短距離,若是咱們此時想要把str1a這個字符串變成str2b這個字符串,咱們有以下幾種選擇:字符串

  1. 替換: 在str1變成str2的步驟後,咱們將str1a中的a替換爲b,就獲得str2b (若是ab相等,就不用操做)get

  2. 增長: 在str1a變成str2的步驟後,咱們再在末尾添加一個b,就獲得str2b (str1a先根據已知距離變成str2,再加個b)it

  3. 刪除: 在str1變成str2b的步驟後,對於str1a,咱們將末尾的a刪去,就獲得str2b (str1aa刪去獲得str1,而str1str2b的編輯距離已知)io

根據這三種操做,咱們能夠獲得遞推式
若a和b相等:class

dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i][j])

若a和b不相等:pdf

dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i][j]+1)

由於將一個非空字符串變成空字符串的最小操做數是字母個數(全刪),反之亦然,因此:

dp[0][j]=j, dp[i][0]=i

最後咱們只要返回dp[m][n]便可,其中m是word1的長度,n是word2的長度

詳解請看斯坦福課件

代碼

public class Solution {
    public int minDistance(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m + 1][n + 1];
        // 初始化空字符串的狀況
        for(int i = 1; i <= m; i++){
            dp[i][0] = i;
        }
        for(int i = 1; i <= n; i++){
            dp[0][i] = i;
        }
        for(int i = 1; i <= m; i++){
            for(int j = 1; j <= n; j++){
                // 增長操做:str1a變成str2後再加上b,獲得str2b
                int insertion = dp[i][j-1] + 1;
                // 刪除操做:str1a刪除a後,再由str1變爲str2b
                int deletion = dp[i-1][j] + 1;
                // 替換操做:先由str1變爲str2,而後str1a的a替換爲b,獲得str2b
                int replace = dp[i-1][j-1] + (word1.charAt(i - 1) == word2.charAt(j - 1) ? 0 : 1);
                // 三者取最小
                dp[i][j] = Math.min(replace, Math.min(insertion, deletion));
            }
        }
        return dp[m][n];
    }
}
相關文章
相關標籤/搜索