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. linux 版本中 i386/i686/x86-64/pcc 等的区别

    在查看dpdk官方文档的时候,发现有 这样(kernel - devel.x86_64; kernel - devel.ppc64:glibc.i686)这样的安装包信息,收集了点资料来分析这三者的关 ...

  2. 转:Spring Cache抽象详解

    缓存简介 缓存,我的理解是:让数据更接近于使用者:工作机制是:先从缓存中读取数据,如果没有再从慢速设备上读取实际数据(数据也会存入缓存):缓存什么:那些经常读取且不经常修改的数据/那些昂贵(CPU/I ...

  3. MySQL 分区表原理及数据备份转移实战

    MySQL 分区表原理及数据备份转移实战 1.分区表含义 分区表定义指根据可以设置为任意大小的规则,跨文件系统分配单个表的多个部分.实际上,表的不同部分在不同的位置被存储为单独的表.用户所选择的.实现 ...

  4. 【Spring】Spring之事务处理

    编程式事务 /** * 1. 根据DataSource去创建事务管理器 * 构造方法 , 参数1. DataSource */ DataSourceTransactionManager txManag ...

  5. TextView中显示链接 定义颜色

    <TextView android:id="@+id/textView" android:layout_width="match_parent" andr ...

  6. 编码 GBK 的不可映射字符

    一般做项目公司都会统一要求文件编码类型,很多为了实现应用国际化和本地化和更高的性能,而选用UTF-8而非GBK. 但在开发过程中我们都用的是IDE,只要更改了配置就不用操心了,但有时我们也会用命令行来 ...

  7. Oracle 12C -- shutdown CDB

    SQL> select name,open_mode from v$pdbs; NAME OPEN_MODE ------------------------------ ---------- ...

  8. ADF_Starting系列3_使用ADF开发富Web应用程序之开发User Interface

    内容中包含 base64string 图片造成字符过多,拒绝显示

  9. FaceBook登陆API -- Login with API calls

    Login with API calls Related Topics Understanding sessions FBSession Error handling FBError FBLoginC ...

  10. CTreeCtrl鼠标双击响应函数中怎么知道双击的是哪个子项?

    原帖链接: http://bbs.csdn.net/topics/310185501 楼主: CTreeCtrl鼠标双击响应函数中怎么知道双击的是哪个子项? 6楼: CPoint pt;GetCurs ...