美文网首页
72. 编辑距离

72. 编辑距离

作者: 间歇性发呆 | 来源:发表于2019-11-24 18:00 被阅读0次

    给定两个单词 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
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    动态规划

    需要把两个字符串放在表格中,这就是初始状态,第一个字符存空串


    表格
    class Solution {
        /**
         * 动态规划
         * 1. 状态定义:
         *  f(i, j)=word1的前i个字符转变成world2的前j个字符最少的步骤
         * 2. 状态转移方程:
         *  a. word1[i] == word2[j]:
         *      f(i ,j)= f(i - 1, j - 1)
         *  b. word1[i] != word2[j]:
         *      f(i, j)=min{
         *          f(i - 1, j) + 1,
         *          f(i, j - 1) + 1,
         *          f(i - 1, j - 1) + 1
         *      }
         * 
         * @param word1
         * @param word2
         * @return
         */
        public int minDistance(String word1, String word2) {
            if (word1.length() == 0) {
                return word2.length();
            }
            if (word2.length() == 0) {
                return word1.length();
            }
            // step[0][0]表示两个字符串都是空串
            int[][] step = new int[word1.length() + 1][word2.length() + 1];
            // 初始化开始值
            // 当word2为空串的时候,初始化
            for (int i = 1; i < word1.length() + 1; i++) {
                step[i][0] = i;
            }
            // 当word1为空串的时候,初始化
            for (int i = 1; i < word2.length() + 1; i++) {
                step[0][i] = i;
            }
            // 动态规划逻辑
            for (int i = 1; i < word1.length() + 1; i++) {
                for (int j = 1; j < word2.length() + 1; j++) {
                    char c1 = word1.charAt(i - 1);
                    char c2 = word2.charAt(j - 1);
                    if (c1 == c2) {
                        step[i][j] = step[i - 1][j - 1];
                    } else {
                        step[i][j] = Math.min(Math.min(step[i - 1][j], step[i][j - 1]), step[i - 1][j - 1]) + 1;
                    }
                }
            }
            return step[word1.length()][word2.length()];
        }
    
        public static void main(String[] args) {
            int result = new Solution().minDistance("horse", "ros");
            System.out.println(result);
        }
    }
    
    运行效率

    相关文章

      网友评论

          本文标题:72. 编辑距离

          本文链接:https://www.haomeiwen.com/subject/zfalwctx.html