zoukankan      html  css  js  c++  java
  • Edit Distance 解答

    Question

    Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

    You have the following 3 operations permitted on a word:

    • Insert a character
    • Delete a character
    • Replace a character

    For example, given word1 = "mart" and word2 = "karma", return 3.

    Solution

    DP 四要素:1. State 2. Function 3. Initialization 4. Answer

    令dp[i][j]表示长度为i的word1和长度为j的word2的最小距离。假设末位分别为x和y。那么根据x和y是否相同,考虑情况如下:

    1. x == y

    dp[i][j] = dp[i-1][j-1]

    2. x != y

    a) Delete x => dp[i-1][j] + 1

    b) Insert y => dp[i][j-1] + 1

    c) Replace x with y => dp[i-1][j-1] + 1

    dp[i][j]取a,b,c中最小值。

    public class Solution {
        /**
         * @param word1 & word2: Two string.
         * @return: The minimum number of steps.
         */
        public int minDistance(String word1, String word2) {
            // write your code here
            int len1 = word1.length();
            int len2 = word2.length();
            // dp[i][j] represents min distance for word1[0, i - 1] and word2[0, j - 1]
            int[][] dp = new int[len1 + 1][len2 + 1];
            for (int i = 0; i <= len1; i++) {
                dp[i][0] = i;
            }
            for (int j = 0; j <= len2; j++) {
                dp[0][j] = j;
            }
            for (int i = 1; i <= len1; i++) {
                for (int j = 1; j <= len2; j++) {
                    if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                        dp[i][j] = dp[i - 1][j - 1];
                    } else {
                        // delete word1[i - 1]
                        int x = dp[i - 1][j] + 1;
                        // insert word2[j - 1] into word1
                        int y = dp[i][j - 1] + 1;
                        // replace word1[i - 1] with word2[j - 1]
                        int z = dp[i - 1][j - 1] + 1;
                        dp[i][j] = Math.min(x, y);
                        dp[i][j] = Math.min(dp[i][j], z);
                    }
                }
            }
            return dp[len1][len2];
        }
    }
  • 相关阅读:
    SourceTree 跳过登陆
    input type="file"获取文件名方法
    Chrome浏览器安装vue-devtools插件
    设置文本超出既定宽度隐藏,并显示省略号
    node安装express时找不到pakage.json文件;判断安装成功?
    NoSQL:redis缓存数据库
    NoSQL:Linux操作memcached
    Python:迭代器
    Python函数篇:装饰器
    Python面向对象篇之元类,附Django Model核心原理
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/5980439.html
Copyright © 2011-2022 走看看