leetcode-72-编辑距离

问题:

题解:为应用动态规划,我们定义 dp[i][j] 为从 word1[0..i) 到word2[0..j)转换的的最小次数。
对于基本的情况,将一个字符串转换为一个空的字符串,所需操作的最小值就是字符串长度本身,因此很明显: dp[i][0]=i,dp[0][j]=j
对于一般情况,从 word1[0..i) 到 word2[0..j) ,假设我们已知了从 word1[0..i-1) 到 word2[0..j-1) 转换的次数,可以分两种情况讨论。
if word1[i] == word2[j]
此时的的情况就不用多讲,直接dp[i][j]=dp[i-1][j-1]就可以了。
if word1[i] != word2[j]
此时的情况比较复杂,有以下三种可能性。
  下边含义理解为前边字符串转为后边字符串
(1) 替换。如ror和ros,此时进行替换操作,r->s,此时dp[i][j]=dp[i-1][j-1] + 1;
(2) 删除。如roee和ros,此时进行删除操作,delete s,此时dp[i][j]=dp[i-1][j] + 1
(3) 插入。如roe和ross,此时进行插入操作,insert s,此时dp[i][j]=dp[i][j-1] + 1
此时可以看出当word1[i] != word2[j] ,dp[i][j] = min(dp[i][j]=dp[i-1][j-1] , dp[i][j]=dp[i][j-1] , dp[i][j]=dp[i-1][j]) + 1
 
package com.example.demo;

public class Test72 {

    /**
     * 两个字符串的编辑距离
     * e    5   4   4   3
     * s    4   3   3   2
     * r    3   2   2   2
     * o    2   2   1   2
     * h    1   1   2   3
     * ''   0   1   2   3
     * i/j  ''  r   o   s
     * 状态转移方程:
     * 当word1的第i个字符等于,word2的第j个字符,则
     * dp[i][j] = dp[i-1][j-1]
     * 当不等于时
     * dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
     */
    public int minDistance(String word1, String word2) {
        if (word1 == null || word2 == null) {
            return 0;
        }
        int len1 = word1.length();
        int len2 = word2.length();
        if (len1 == 0 || len2 == 0) {
            return len1 + len2;
        }

        int[][] dp = new int[len1 + 1][len2 + 1];
        // 初始化 当空串word1,转换为串word2需要的步数 ,即dp[0][j]
        // 初试话 当串word1,转换为空串word2需要的部署,即dp[i][0]
        for (int i = 0; i < len1 + 1; i++) {
            dp[i][0] = i;
        }
        for (int i = 0; i < len2 + 1; i++) {
            dp[0][i] = i;
        }
        // 动态规划状态转移方程
        for (int i = 1; i < len1 + 1; i++) {
            for (int j = 1; j < len2 + 1; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i - 1][j - 1])) + 1;
                }
            }
        }

        return dp[len1][len2];
    }


    public static void main(String[] args) {
        Test72 t = new Test72();
        int i = t.minDistance("horse", "ros");
        System.out.println(i);
    }
}

 

posted @ 2019-08-14 14:50  xj-record  阅读(282)  评论(0编辑  收藏  举报