LeetCode題解:Edit Distance

題目


Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

Insert a character
Delete a character
Replace a character
Example 1:

Input: word1 = “horse”, word2 = “ros”
Output: 3
Explanation:
horse -> rorse (replace ‘h’ with ‘r’)
rorse -> rose (remove ‘r’)
rose -> ros (remove ‘e’)
Example 2:

Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)

題目分析

給定兩個字符串,其中一個字符串可以通過插入,刪除,替換的方式變成和另一個字符串完全相同,求最小的變換次數。

採用動態規劃算法,假定狀態(i,j)是兩個字符串的第i、j個字符,a[i][j]表示word1.substr(0,i+1)和word2.substr(0,i+1)之間的最小編輯距離,這時a[i][j]= min(a[i-1][j]+1,a[i][j-1]+1,word1.charAt(i)==word2.charAt(j)?a[i][j]:a[i-1][j-1]+1);即狀態(i,j)通過在(i-1,j)插入一個字符,(i,j-1),(i-1,j-1)替換一個字符中的最小值,注意如果i,j兩個字符相同,那麼不需要替換。

二維數組a是(m+1)*(n+1)的字符串,因爲子串包含空串。

/**
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
var minDistance = function(word1, word2) {
    var m = word1.length,n = word2.length;
    var a = new Array(m+1);
    for(var i = 0;i <= m;i++) a[i] = new Array(n+1);
    
    for(i = 0;i <= m;i++) a[i][0] = i;
    for(i = 0;i <= n;i++) a[0][i] = i;
    
    for(i = 1;i <= m;i++){
        for(var j = 1;j <= n;j++){
            var m1 = a[i-1][j] + 1;
            var m2 = a[i][j-1] + 1;
            if(word1.charAt(i-1) == word2.charAt(j-1)){
                var m3 = a[i-1][j-1];
            }else {
                m3 = a[i-1][j-1] + 1;   
            }
            var mm = Number.MAX_VALUE;
            if(mm > m1) mm = m1;
            if(mm > m2) mm = m2;
            if(mm > m3) mm = m3;
            a[i][j] = mm;
        }
    }
    return a[m][n];
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章