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];
        }
    }
  • 相关阅读:
    log4net简介(四)
    Log4net简介(二)
    详解制作集成SP2的Windows2003安装光盘
    给Fedora11安装声卡驱动
    CSS背景色的半透明设置
    利用事务日志来误操作恢复与灾难恢复
    log4net简介(三)之无法写入日志
    能盖住Select的Div
    SQLServer将日期转换成字符串格式
    如何在 Windows 恢复环境中使用 Bootrec.exe 工具解决和修复 Windows Vista 中的启动问题
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/5980439.html
Copyright © 2011-2022 走看看