题目
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];
};