1*b8c85eecS猫头猫function makeMatrix(row: number, col: number) { 2*b8c85eecS猫头猫 return Array(row) 3*b8c85eecS猫头猫 .fill(0) 4*b8c85eecS猫头猫 .map(_ => Array(col).fill(Infinity)); 5*b8c85eecS猫头猫} 6*b8c85eecS猫头猫 7*b8c85eecS猫头猫export default function minDistance(word1?: string, word2?: string): number { 8*b8c85eecS猫头猫 if (!word1 || !word2) { 9*b8c85eecS猫头猫 return word1?.length || word2?.length || 0; 10*b8c85eecS猫头猫 } 11*b8c85eecS猫头猫 12*b8c85eecS猫头猫 const dp = makeMatrix(word1.length + 1, word2.length + 1); 13*b8c85eecS猫头猫 14*b8c85eecS猫头猫 for (let i = 0; i <= word1.length; ++i) { 15*b8c85eecS猫头猫 for (let j = 0; j <= word2.length; ++j) { 16*b8c85eecS猫头猫 if (i === 0 || j === 0) { 17*b8c85eecS猫头猫 dp[i][j] = i || j; 18*b8c85eecS猫头猫 continue; 19*b8c85eecS猫头猫 } 20*b8c85eecS猫头猫 const currentStr1 = word1[i - 1]; 21*b8c85eecS猫头猫 const currentStr2 = word2[j - 1]; 22*b8c85eecS猫头猫 if (currentStr1 === currentStr2) { 23*b8c85eecS猫头猫 dp[i][j] = Math.min( 24*b8c85eecS猫头猫 dp[i - 1][j - 1], 25*b8c85eecS猫头猫 dp[i - 1][j] + 1, 26*b8c85eecS猫头猫 dp[i][j - 1] + 1, 27*b8c85eecS猫头猫 ); 28*b8c85eecS猫头猫 } else { 29*b8c85eecS猫头猫 dp[i][j] = Math.min( 30*b8c85eecS猫头猫 dp[i - 1][j - 1] + 1, 31*b8c85eecS猫头猫 dp[i - 1][j] + 1, 32*b8c85eecS猫头猫 dp[i][j - 1] + 1, 33*b8c85eecS猫头猫 ); 34*b8c85eecS猫头猫 } 35*b8c85eecS猫头猫 } 36*b8c85eecS猫头猫 } 37*b8c85eecS猫头猫 38*b8c85eecS猫头猫 return dp[word1.length][word2.length]; 39*b8c85eecS猫头猫} 40