LeetCode-72. Edit Distance

来源:互联网 发布:舆情监控软件下载 编辑:程序博客网 时间:2024/06/07 07:37

一、问题描述

  1. 给定两个字符串word1和word2,通过插入一个字符、删除一个字符、替换一个字符操作将word1变为word2,返回变换的最小步骤数。
  2. 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

二、解题思路

  1. 思路参考这篇博客,利用动态规划的思想。dp[i][j]表示以word1[i]结尾的字符串和以word2[j]结尾的字符串转换需要的最小操作数。
    • 替换
      如果word1[i-1]与word2[j-1]已对齐,即dp[i-1][j-1]已知,则当word1[i]==word2[j]时,dp[i][j]=dp[[i-1][j-1];否则dp[i][j]=dp[i-1][j-1]+1.
    • 删除
      如果word1[i-1]与word2[j]已对齐,需要删除多出来的word1[i],则dp[i][j]=dp[i-1][j]+1.
    • 插入
      如果word1[i]与word2[j-1]已对齐,则需要在word1[i]后面添加word2[j],则dp[i][j]=dp[i][j-1]+1.
  2. 空间优化
    参照1中的思路,计算dp[i][j]用到了dp[i-1][j-1],dp[i][j-1],dp[i-1][j],而与其他的位置无关,因此仅需要有一个变量记录dp[i-1][j-1],就可以将dp变为一维数组。

三、代码

动态规划

public class Solution {    public int minDistance(String word1, String word2) {        if(word1.length()==0)            return word2.length();        if(word2.length()==0)            return word1.length();        int m=word1.length(),n=word2.length();        int[][] dp=new int[m+1][n+1];        for(int i=0;i<m+1;i++){            dp[i][0]=i;        }        for(int j=0;j<n+1;j++){            dp[0][j]=j;        }        for(int i=1;i<m+1;i++){            for(int j=1;j<n+1;j++){                dp[i][j]=Math.min(dp[i-1][j-1]+(word1.charAt(i-1)==word2.charAt(j-1)?0:1),Math.min(dp[i-1][j]+1,dp[i][j-1]+1));            }        }        return dp[m][n];    }}

空间优化

public class Solution {    public int minDistance(String word1, String word2) {        if(word1.length()==0)            return word2.length();        if(word2.length()==0)            return word1.length();        int m=word1.length(),n=word2.length();        int[] dp=new int[n+1];        for(int i=0;i<m+1;i++){            int last=0;            for(int j=0;j<n+1;j++){                if(i==0){                    dp[j]=j;                }else if(j==0){                    last=dp[0];                    dp[0]=i;                }else{                    int temp=dp[j];                    dp[j]=Math.min(last+(word1.charAt(i-1)==word2.charAt(j-1)?0:1),Math.min(dp[j]+1,dp[j-1]+1));                    last=temp;                }            }        }        return dp[n];    }}
原创粉丝点击