Edit Distance

来源:互联网 发布:荣威rx5 安装软件 编辑:程序博客网 时间:2024/05/10 07:55

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

分析:
http://blog.csdn.net/linhuanmars/article/details/24213795

这其实是一道二维动态规划的题目,模型上确实不容易看出来,下面我们来说说递推式。
我们维护的变量res[i][j]表示的是word1的前i个字符和word2的前j个字符编辑的最少操作数是多少。假设我们拥有res[i][j]前的所有历史信息,看看如何在常量时间内得到当前的res[i][j],我们讨论两种情况:
1)如果word1[i-1]=word2[j-1],也就是当前两个字符相同,也就是不需要编辑,那么很容易得到res[i][j]=res[i-1][j-1],因为新加入的字符不用编辑;
2)如果word1[i-1]!=word2[j-1],那么我们就考虑三种操作,如果是插入word1,那么res[i][j]=res[i-1][j]+1,也就是取word1前i-1个字符和word2前j个字符的最好结果,然后添加一个插入操作;如果是插入word2,那么res[i][j]=res[i][j-1]+1,道理同上面一种操作;如果是替换操作,那么类似于上面第一种情况,但是要加一个替换操作(因为word1[i-1]和word2[j-1]不相等),所以递推式是res[i][j]=res[i-1][j-1]+1。上面列举的情况包含了所有可能性,有朋友可能会说为什么没有删除操作,其实这里添加一个插入操作永远能得到与一个删除操作相同的效果,所以删除不会使最少操作数变得更好,因此如果我们是正向考虑,则不需要删除操作。取上面几种情况最小的操作数,即为第二种情况的结果,即res[i][j] = min(res[i-1][j], res[i][j-1], res[i-1][j-1])+1。
接下来就是分析复杂度,算法时间上就是两层循环,所以时间复杂度是O(m*n),空间上每一行只需要上一行信息,所以可以只用一维数组即可,我们取m, n中小的放入内层循环,则复杂度是O(min(m,n))

LS这个二维动态规划很是熟练啊,快得到真传了

二维分析,一维写代码,赞!

public class Solution {    public int minDistance(String word1, String word2) {    if(word1.length()==0)        return word2.length();    if(word2.length()==0)        return word1.length();    String minWord = word1.length()>word2.length()?word2:word1;    String maxWord = word1.length()>word2.length()?word1:word2;    int[] res = new int[minWord.length()+1];    for(int i=0;i<=minWord.length();i++)    {        res[i] = i;    }    for(int i=0;i<maxWord.length();i++)    {        int[] newRes = new int[minWord.length()+1];        newRes[0] = i+1;        for(int j=0;j<minWord.length();j++)        {            if(minWord.charAt(j)==maxWord.charAt(i))            {                newRes[j+1]=res[j];            }            else            {                newRes[j+1] = Math.min(res[j],Math.min(res[j+1],newRes[j]))+1;            }        }        res = newRes;    }    return res[minWord.length()];  }}


0 0