Mike-Zhu / note

note
3 stars 1 forks source link

eidt-diatance #3

Open Mike-Zhu opened 5 years ago

Mike-Zhu commented 5 years ago
var minDistance = function (word1, word2) {
    var len1 = word1.length
    var len2 = word2.length
    var d = Array.from({ length: len2 + 1 })
        .map(
            () => Array.from({ length: len1 + 1 })
        )
    for (var i = 0; i < len2 + 1; i++) {
        d[i][0] = i
    }
    for (var j = 0; j < len1 + 1; j++) {
        d[0][j] = j
    }
    for (var i = 1; i < len2 + 1; i++) {
        for (var j = 1; j < len1 + 1; j++) {
            let prev = d[i - 1][j - 1]
            let cont = word2[i - 1] === word1[j - 1] ? 0 : 1
            d[i][j] = Math.min(
                d[i - 1][j] + 1,
                d[i][j - 1] + 1,
                prev + cont,
            )
        }
    }
    return d[len2][len1]
};

最小编辑距离代码块