`

LeetCode - 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:

The following recurrence relations define the edit distance, d(s1,s2), of two strings s1 and s2:

d('', '') = 0               -- '' = empty string
d(s, '')  = d('', s) = |s|  -- i.e. length of s
d(s1+ch1, s2+ch2)
  = min( d(s1, s2) + if ch1=ch2 then 0 else 1 fi,
         d(s1+ch1, s2) + 1,
         d(s1, s2+ch2) + 1 )

The first two rules above are obviously true, so it is only necessary consider the last one. Here, neither string is the empty string, so each has a last character, ch1 and ch2 respectively. Somehow, ch1 and ch2 have to be explained in an edit of s1+ch1 into s2+ch2. If ch1 equals ch2, they can be matched for no penalty, i.e. 0, and the overall edit distance is d(s1,s2). If ch1 differs from ch2, then ch1 could be changed into ch2, i.e. 1, giving an overall cost d(s1,s2)+1. Another possibility is to delete ch1 and edit s1 into s2+ch2, d(s1,s2+ch2)+1. The last possibility is to edit s1+ch1 into s2 and then insert ch2, d(s1+ch1,s2)+1. There are no other alternatives. We take the least expensive, i.e. min, of these alternatives.

 

A two-dimensional matrix, m[0..|s1|,0..|s2|] is used to hold the edit distance values:

m[i,j] = d(s1[1..i], s2[1..j])

m[0,0] = 0
m[i,0] = i,  i=1..|s1|
m[0,j] = j,  j=1..|s2|

m[i,j] = min(m[i-1,j-1]
             + if s1[i]=s2[j] then 0 else 1 fi,
             m[i-1, j] + 1,
             m[i, j-1] + 1 ),  i=1..|s1|, j=1..|s2|

m[,] can be computed row by row. Row m[i,] depends only on row m[i-1,]. The time complexity of this algorithm is O(|s1|*|s2|). If s1 and s2 have a `similar' length, about `n' say, this complexity is O(n2), much better than exponential!

 

public int minDistance(String word1, String word2) {
    int m = word1.length(), n = word2.length();
    int[][] f = new int[m+1][n+1];
    for(int i=0; i<=m; i++) {
        f[i][0] = i;
        for(int j=0; j<=n; j++) {
            if(i==0) f[0][j] = j;
            else if(j!=0) f[i][j] = Integer.MAX_VALUE; //注意,其他元素初始化为INT_MAX
        }
    }

    for(int i=1; i<=m; i++) {
        for(int j=1; j<=n; j++) {
            int diff = (word1.charAt(i-1) != word2.charAt(j-1)) ? 1 : 0;
            f[i][j] = Math.min(f[i][j], f[i-1][j-1]+diff); //replace if cost=1
            f[i][j] = Math.min(f[i][j], f[i-1][j]+1); //delete
            f[i][j] = Math.min(f[i][j], f[i][j-1]+1); //insert
        }
    }
    return f[m][n];
}

 

Reference:

http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Dynamic/Edit/

分享到:
评论

相关推荐

    python-leetcode题解之072-Edit-Distance

    python python_leetcode题解之072_Edit_Distance

    c语言-leetcode题解之0072-edit-distance.zip

    c c语言_leetcode题解之0072_edit_distance.zip

    python-leetcode题解之161-One-Edit-Distance.py

    python python_leetcode题解之161_One_Edit_Distance.py

    _leetcode-python.pdf

    - Edit Distance: 给定两个单词word1和word2,计算将word1转换为word2所使用的最少操作数。 - Set Matrix Zeroes: 给定一个m×n的矩阵,如果一个元素为0,则将其所在行和列的所有元素都变为0。 - Search a 2D Matrix...

    LeetCode最全代码

    477 | [Total Hamming Distance](https://leetcode.com/problems/total-hamming-distance/) | [C++](./C++/total-hamming-distance.cpp) [Python](./Python/total-hamming-distance.py) | _O(n)_ | _O(1)_ | Medium ...

    leetcode分类-LeetCode:力码

    Distance Maximum Subarray Minimum Path Sum Unique Paths Unique Paths II Longest Palindromic Substring Interleaving String Triangle Distinct Subsequences Decode Ways Palindrome Partitioning II Maximal ...

    leetcode316-algorithm-code-csharp:C#算法题汇总

    10. LeetCode第1081题:"One Edit Distance"(单编辑距离):判断两个字符串之间是否只需要一次编辑操作(插入、删除或替换)就可以互相转换。 11. LeetCode第1310题:"XOR Queries of a Subarray"(子数组异或查询...

    leetcode中国-Algorithms:算法

    leetcode中国英文翻译正在进行中... 一些文章仍然是中文的,但大部分已经完成。 请为这个 repo 加注星标。 完整的翻译最终将完成。 享受。...这些文章讨论了不同类型的...Programming/EditDistance.md) 【经典DP:超级蛋

    python-leetcode面试题解之第161题相隔为1的编辑距离-题解.zip

    在本压缩包中,我们关注的是一个Python编程与算法相关的面试题目,具体是LeetCode的第161题,名为“相隔为1的编辑距离”(Edit Distance)。这个题目在求职面试中常被用来测试候选人的编程能力,特别是对字符串操作...

    php-leetcode题解之编辑距离.zip

    编辑距离(Edit Distance)是一种衡量两个字符串相似度的算法,广泛应用于编程竞赛、文本处理、搜索引擎优化等领域。在LeetCode这个知名的在线编程挑战平台上,它是一个经典的算法问题。本资料包是关于使用PHP解决...

    python-leetcode面试题解之第72题编辑距离.zip

    在LeetCode的面试题目中,第72题“编辑距离”(Edit Distance)是一个经典的算法问题,它涉及到了字符串操作、动态规划和递归等编程概念。本题解将深入探讨这个问题的背景、解决方案以及Python实现。 ### 问题背景 ...

    Leetcode book刷题必备

    14. One Edit Distance:判断两个字符串是否只差一个字符操作。 15. Read N Characters Given Read4:一次调用 read4() 可以读取 4 个字符,编写一个函数,使其能够读取 n 个字符。 16. Read N Characters Given ...

    leetcode正则表达式-DP-7:DP-7

    "Edit Distance"(编辑距离)是动态规划的一个经典应用,通常用于计算两个字符串之间的最小操作次数,使得一个字符串转换成另一个。这些操作可能包括插入、删除和替换字符。"Regular Expression Matching"(正则...

    c++-c++编程基础之leetcode题解第72题编辑距离.zip

    标题"**c++-c++编程基础之leetcode题解第72题编辑距离.zip**"指的是一个关于C++编程的学习资源,特别针对LeetCode网站上的第72题“编辑距离”(Edit Distance)的问题。LeetCode是一个在线平台,提供了各种算法题目...

    gasstationleetcode-leetcode:LeetcodeOJ解决方案

    leetcode 【演示记录】 报告 展示 2017/03/06 1.二和,167.二和二 2107/03/06 15.3 总和,16.3 总和最近,18.4 总和,11.最多水的容器 2017/03/09 62.Unique Paths, 63.Unique Paths II, 64.Minimum Path Sum 2017/...

    uber leetcode

    #### 十、One Edit Distance - **知识点:**动态规划、字符串比较。 - **题目描述:**给定两个字符串word1和word2,返回使word1和word2相同所需的最小步数。每步可以插入一个字符、删除一个字符或者替换一个字符。 -...

    LeetCode判断字符串是否循环-data-structure-and-algo:C++中的数据结构和算法

    EditDistance(#72) 图 : 集合的合并(直接求并、按大小求并和按深度求并)、根搜寻(路径压缩) : 有向图和无向图的邻接表表示方法 : 图的深度优先和广度优先搜索(假设图用邻接表矩阵表示)、拓扑排序、判断是否有环 ...

    lrucacheleetcode-problem-solving:技术面试题和一些竞争性编程题

    lru缓存leetcode 解决问题 用于技术面试和竞争性编程的算法和数据结构。...edit_distance.rs:在练习 Rust 的同时逐渐编写编辑距离变化。 7- trie.py:只是trie/prefix-tree 的几个实现。 8- LRU.py:LRU 缓存实

    算法导论_编辑距离1

    《算法导论》中的编辑距离(Edit Distance)是一个在计算机科学和信息处理中常见的概念,用于衡量两个字符串之间的差异。编辑距离定义为将一个字符串转换成另一个字符串所需的最少单字符编辑操作次数,这些操作包括...

    airbnb 软件工程师面试题

    #### K Edit Distance(K次编辑距离) - **概念解释**:编辑距离是指两个字符串之间,由一个转换成另一个所需的最少编辑操作次数。 - **实现细节**: - 使用动态规划求解。 - 考虑插入、删除和替换三种操作。 ###...

Global site tag (gtag.js) - Google Analytics