72. Edit Distance (DP)

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: 
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: 
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

感想:作为CS的学生居然研一才在徐雷老师的基因组学大数据课上第一次知道这类问题,当时真的大开眼界!自学能力和主动性真的很低了,唯一可以激起我学习动力的就是真金白银了,所以长线的大饼不适合我,注定是一个眼光比较短浅追求快钱的人啊(没大出息!(′д` )…彡…彡)没办法,只好向钱看齐啦~好好学习。

动态规划问题

将大问题通过分解递归解决,重点是总结出递归表达式,通过分解问题和整体之间的关系逐步击破。

容易出问题的地方有:忘记初始化,边界考虑不清,数组等数据结构的使用

题目分析:

参考官方solution。本题目是求两个字符串之间的最小编辑距离。

编辑距离的意义:

The edit distance algorithm is very popular among the data scientists. It's one of the basic algorithms used for evaluation of machine translation and speech recognition.

定义数组D[i][j]代表word1前i个元素的substring与word2前j个元素的substring 的编辑距离。那么有两种情形:

1. 如果word1[i]==word2[j], D[i][j]至少可以是D[i-1][j-1],那么还可能是1+min(D[i][j-1],D[i-1][j])

2. 如果两个字符不同,那么D[i][j]应该是min(D[i][j-1],D[i-1][j],D[i-1][j-1])+1

所以总结i起来

compute

可以看一下官方给出的动态过程:

https://leetcode.com/problems/edit-distance/solution/

一个小技巧在判断字符串是否有空~在递归之前判断一下可以避免不必要的循环。

注意初始化的时候,D[i][j]中,如果i=0,D[0][j]=j, D[i][0]=i

 public int minDistance(String word1, String word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        if(len1*len2==0)//注意这里有一个技巧判断是否有一个字符串为空
            return len1+len2;
        int[][] D = new int[len1+1][len2+1];
        D[0][0] = 0;
        for(int i=1;i<len1+1;i++)
            D[i][0] = i;
        for(int i=1;i<len2+1;i++)
            D[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))
                    D[i][j] = Math.min(D[i-1][j-1], 1+Math.min(D[i][j-1], D[i-1][j]));
                else
                    D[i][j] = Math.min(D[i-1][j-1], Math.min(D[i][j-1], D[i-1][j]))+1;
            }
        }
        return D[len1][len2];
    }

猜你喜欢

转载自blog.csdn.net/shulixu/article/details/86413702