Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

编辑距离-72 #119

Open
sl1673495 opened this issue Jul 25, 2020 · 0 comments
Open

编辑距离-72 #119

sl1673495 opened this issue Jul 25, 2020 · 0 comments
Labels
动态规划 待复习 看题解或者做出来很艰难的,需要回顾。

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jul 25, 2020

给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

插入一个字符
删除一个字符
替换一个字符
 

示例 1:

输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')

示例 2:

输入:word1 = "intention", word2 = "execution"
输出:5
解释:
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/edit-distance
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

参考 weiwei 兄的题解即可。
https://leetcode-cn.com/problems/edit-distance/solution/dong-tai-gui-hua-java-by-liweiwei1419

/**
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
let minDistance = function (word1, word2) {
    let l1 = word1.length
    let l2 = word2.length

    if (!l1) {
        return l2
    }
    if (!l2) {
        return l1
    }

    let dp = []
    dp[0] = [0]
    // 基础状态 从空字符串转变成另一个字符串只能靠增加操作 每个字符耗费 1 操作数
    for (let i = 1; i <= l1; i++) {
        dp[i] = []
        dp[i][0] = i
    }
    for (let j = 1; j <= l2; j++) {
        dp[0][j] = j
    }

    for (let i = 0; i < l1; i++) {
        for (let j = 0; j < l2; j++) {
            // 相等的话 不需要编辑 直接取各退一位的最小距离即可
            if (word1[i] === word2[j]) {
                dp[i + 1][j + 1] = dp[i][j]
                continue
            }

            let insert = dp[i + 1][j] + 1
            let remove = dp[i][j + 1] + 1
            let modify = dp[i][j] + 1

            dp[i + 1][j + 1] = Math.min(insert, remove, modify)
        }
    }

    return dp[l1][l2]
};
@sl1673495 sl1673495 added 动态规划 待复习 看题解或者做出来很艰难的,需要回顾。 labels Jul 25, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
动态规划 待复习 看题解或者做出来很艰难的,需要回顾。
Projects
None yet
Development

No branches or pull requests

1 participant