zoukankan      html  css  js  c++  java
  • 最小编辑距离

    给定两个单词 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')

    /**
     * @param {string} word1
     * @param {string} word2
     * @return {number}
     */
    var minDistance = function(word1, word2) {
            let temp = new Array();
        let n = word1.length;
        let m = word2.length;
        if(n==0||m==0){
            return n>m? n:m;
        }
       
        for(let i=0;i<=n;i++){
            let demo = new Array();
            for(let j=0;j<=m;j++){
                demo[j] = 0;
            }
            temp.push(demo);
        }
    
        for(let i = 1;i<=n;i++){
            temp[i][0] = i;
        }
        for(let j=1;j<=m;j++){
            temp[0][j] = j;
        }
    
        for(let i=1;i<=n;i++){
            for(let j=1;j<=m;j++){
                if(word1[i-1]== word2[j-1]){
                    temp[i][j] = temp[i-1][j-1];
                }else{
                    temp[i][j] = Math.min(
                        temp[i][j-1]+1,
                        temp[i-1][j]+1,
                        temp[i-1][j-1]+1
                    )
                }
            }
        }
        return temp[n][m];
    };

    动态规划

    https://leetcode-cn.com/problems/edit-distance/solution/bian-ji-ju-chi-mian-shi-ti-xiang-jie-by-labuladong/

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

  • 相关阅读:
    android system.img
    ab压力测试和CC预防
    ubuntu工具积累
    ViewManager
    PopupWindow
    singleton注意
    java byte[]生成
    java有符号无符号的转换
    C#垃圾回收Finalize 和Dispose的理解
    Silverlight 获取汉字拼音首字母
  • 原文地址:https://www.cnblogs.com/panjingshuang/p/11801504.html
Copyright © 2011-2022 走看看