Edit Distance

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

SOLUTION 1:

REF:
http://www.cnblogs.com/etcow/archive/2012/08/30/2662985.html
http://www.cnblogs.com/etcow/archive/2012/08/30/2662985.html
http://blog.csdn.net/fightforyourdream/article/details/13169573
http://www.cnblogs.com/TenosDoIt/p/3465316.html

相当经典的一道递归题目,而且难度级别为4.


这是一个典型的2维DP.
定义D[i][j] 为string1 前i个字符串到 string2的前j个字符串的转化的最小步。
1. 初始化: D[0][0] = 0;  2个为空 不需要转
2. D[i][0] = D[i - 1][0] + 1. 就是需要多删除1个字符
3. D[0][j] = D[0][j - 1] + 1. 就是转完后需要添加1个字符

D[i][j] 的递推公式:
我们来考虑最后一步的操作:
从上一个状态到D[i][j],最后一步只有三种可能:
添加,删除,替换(如果相等就不需要替换)

a、给word1插入一个和word2最后的字母相同的字母,这时word1和word2的最后一个字母就一样了,此时编辑距离等于1(插入操作) + 插入前的word1到word2去掉最后一个字母后的编辑距离
D[i][j - 1] + 1
例子:  从ab --> cd
我们可以计算从 ab --> c 的距离,也就是 D[i][j - 1],最后再在尾部加上d

b、删除word1的最后一个字母,此时编辑距离等于1(删除操作) + word1去掉最后一个字母到word2的编辑距离
D[i - 1][j] + 1
例子:  从ab --> cd
我们计算从 a --> cd 的距离,再删除b, 也就是 D[i - 1][j] + 1

c 、把word1的最后一个字母替换成word2的最后一个字母,此时编辑距离等于 1(替换操作) + word1和word2去掉最后一个字母的编辑距离。
这里有2种情况,如果最后一个字符是相同的,即是:D[i - 1][j - 1],因为根本不需要替换,否则需要替换,就是
D[i - 1][j - 1] + 1

然后取三种情况下的最小距离

现在来证明一下,当最后一个字符相同时,D[i][j] = D[i - 1][j - 1],这里只要证明D[i - 1][j -1] <=D[i ][j - 1]+1即可。
反证法:
假设:D[i - 1][j -1] > D[i ][j - 1]+1
推论:如果我们要把i-1字符串变换为j - 1,
          我们可以通过先在str1加上一个字符,得到带前i个字符的str1 , 然后再执行D[i][j -1]
          D[i][j - 1] + 1 也可以推出 i , j 字符串的转换  也就是说
          推出:D[i - 1][j - 1]不是i - 1--> j - 1转换的最小值
          推论与题设相矛盾,所以得证。

基于以上证明,当最后一个字符相同时,我们其实可以直接让D[i][j] = D[i - 1][j - 1].

例子: "ababd" -> "ccabab"

  先初始化matrix如下。意思是,比如"_" -> "cca" = 2 操作是插入'c','c','a',共3步。 "abab" -> "+ "_" 删除'a','b','a','b',共4 步。

  _ a b a b d
_ 0 1 2 3 4 5
c 1          
c 2          
a 3          
b 4          
a 5          
b 6          

  然后按照注释里的方法填满表格,返回最后一个数字(最佳解)

  _ a b a b d
_ 0 1 2 3 4 5
c 1 1 2 3 4 5
c 2 2 2 3 4 5
a 3 2 3 2 3 4
b 4 3 2 3 2 3
a 5 4 3 2 3 3
b 6 5 4 3 2 3
 public class Solution {
public int minDistance(String word1, String word2) {
if (word1 == null || word2 == null) {
return 0;
} int len1 = word1.length();
int len2 = word2.length(); int[][] D = new int[len1 + 1][len2 + 1]; for (int i = 0; i <= len1; i++) {
for (int j = 0; j <= len2; j++) {
if (i == 0) {
D[i][j] = j;
} else if (j == 0) {
D[i][j] = i;
} else {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
D[i][j] = D[i - 1][j - 1];
} else {
D[i][j] = Math.min(D[i - 1][j - 1], D[i][j - 1]);
D[i][j] = Math.min(D[i][j], D[i - 1][j]);
D[i][j]++;
}
}
}
} return D[len1][len2];
}
}

GitHub代码链接

Leetcode:Edit Distance 解题报告的更多相关文章

  1. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  2. [LeetCode] Edit Distance 编辑距离

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

  3. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  4. LeetCode - Course Schedule 解题报告

    以前从来没有写过解题报告,只是看到大肥羊河delta写过不少.最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手. 原题链接 https://leetcode.com/problems/c ...

  5. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

  6. 【LeetCode】461. Hamming Distance 解题报告(java & python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 方法一:异或 + 字符串分割 方法二: ...

  7. 【LeetCode】477. Total Hamming Distance 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 位运算 日期 题目地址:https://leetco ...

  8. 【LeetCode】243. Shortest Word Distance 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcode ...

  9. LeetCode 461 Hamming Distance 解题报告

    题目要求 The Hamming distance between two integers is the number of positions at which the corresponding ...

随机推荐

  1. 【LeetCode】174. Dungeon Game

    Dungeon Game The demons had captured the princess (P) and imprisoned her in the bottom-right corner ...

  2. 【LeetCode】173. Binary Search Tree Iterator (2 solutions)

    Binary Search Tree Iterator Implement an iterator over a binary search tree (BST). Your iterator wil ...

  3. YAML 语言教程(转载)

    用YAML语言读取配置是最快的,之前的suricata中用yaml读取了配置,并且在代码运行期间,对配置进行了维护,所以抽点时间,来了解一下YAML语言编程,下文虽然对YAML语言和JAVAScrip ...

  4. RHEL/CentOS 7.x/6.x/5.x开启EPEL仓库

    说明 原文链接 翻译:@adolphlwq 项目地址 这篇指南文章教你如何在 RHEL/CentOS 7.x/6.x/5.x 系统中开启EPEL仓库支持,以便你可以使用 yum 命令 安装额外的标准开 ...

  5. permission denied (publickey)问题的解决 和 向github添加ssh key

    使用ssh key这种方式进行clone ,pull github上面的项目,使用 git clone或者git pull origin master出现permission denied (publ ...

  6. 使用Nexus搭建Maven服务器详细配置【转】

    为什么要搭建nexus私服,原因很简单,有些公司都不提供外网给项目组人员,因此就不能使用maven访问远程的仓库地址,所以很有必要在局域网里找一台有外网权限的机器,搭建nexus私服,然后开发人员连到 ...

  7. log4j(四)——如何控制不同风格的日志信息的输出?

    一:测试环境与log4j(一)——为什么要使用log4j?一样,这里不再重述 二:老规矩,先来个栗子,然后再聊聊感受 import org.apache.log4j.*; //by godtrue p ...

  8. numpy中的np.random.mtrand.RandomState

    1 RandomState 的应用场景概述 在训练神经网络时,苦于没有数据,此时numpy为我们提供了 “生产” 数据集的一种方式. 例如在搭建神经网络(一)中的 4.3 准备数据集 章节中就是采用n ...

  9. svn开发常用整理

    1.删除tortoise svn中的账号信息 其实tortoise svn也是将账号信息存放在本地的配置文件中 在不同的操作系统下,操作基本类似,首先我们来看一下windows下如何操作的. 以win ...

  10. mvc 使用预置队列类型存储异常对象

    using PaiXie.Utils; using System; using System.Collections.Generic; using System.Linq; using System. ...