Edit Distance

来源:互联网 发布:我的世界linux服务端 编辑:程序博客网 时间:2024/04/26 19:02

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:

a) Insert a character
b) Delete a character

c) Replace a character


总结:什么问题可以用DP来解?

1 DP的定义:就是原来的大问题,可以分解为小问题,这些子问题具有重复性,我们就保存起来,并且,原来的问题是由子问题的最优解得到的,相互之间有依赖性。这样我们就要用dp。

Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems and stores the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming.

1) Overlapping Subproblems
2) Optimal Substructure

思路:想把str1变成str2. 从后往前进行变化,这样变化之后,又变成同样的类似的子问题。这题也可以递归写,详情见:http://www.geeksforgeeks.org/dynamic-programming-set-5-edit-distance/ 复杂度是O(3^m),是个指数级的复杂度。然后画状态树,可以发现有重复子问题,这样,可以用dp解决。dp就是记录之前算过的结果,然后以后用到拿过来用就行,不用重复计算。可以想象成i, j 指针分别指向str1和str2. 

str1是m长度,str2是n长度。

如果str1.charAt(i) == str2.charAt(j) ,则 i, j 分别前面移动,比较下一个。

如果不同,可以有三种变换方式:

insert:  子问题变成 m,n-1  (想象一下,str1后面insert了一个字符和str2的最后一个字符相同)i在m不变,j往前移动一位。所以j-1.

delete:  子问题变成 m-1, n (str1的元素少一个,i变成m-1,j还在n位置不动,再进行比较)

update: 子问题变成 m-1, n-1 (也就是,update之后,i,j都往前移动)

最后输出dp(m,n)的值.

public class Solution {    public int minDistance(String word1, String word2) {        int[][] matrix = new int[word1.length()+1][word2.length()+1];                for(int i=0; i<word1.length()+1;i++) {            matrix[i][0]=i;        }                for(int i=0; i<word2.length()+1;i++){            matrix[0][i]=i;        }                for(int i=1; i<word1.length()+1;i++){            for(int j=1; j<word2.length()+1; j++){                if(word1.charAt(i-1) == word2.charAt(j-1)){                    matrix[i][j] = matrix[i-1][j-1];                }else{                    int replace = matrix[i-1][j-1]+1;                    int insert = matrix[i][j-1]+1;                    int delete = matrix[i-1][j]+1;                    matrix[i][j]=Math.min(Math.min(replace,insert),delete);                }            }        }       return matrix[word1.length()][word2.length()];    }}


0 0