未验证 提交 6036fa80 编写于 作者: K Keqi Huang 提交者: GitHub

Update 072._edit_distance.md

上级 d5508eda
### 72. Edit Distance
# 72. Edit Distance
题目:
<https://leetcode.com/problems/edit-distance/>
**<font color=red>难度: Hard</font>**
## 刷题内容
难度:
> 原题连接
Hard
* https://leetcode.com/problems/edit-distance/description/
> 内容描述
```
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
```
## 解题方案
> 思路 1
******- 时间复杂度: O(len(word1)*len(word2))******- 空间复杂度: O(len(word1)*len(word2))******
可以做的操作:
......@@ -48,39 +83,7 @@ Hard
***要始终明确一点,```dp[i][j]```的含义是使得```word1的前i字符子串```与```word2的前j字符子串```相等所需要的操作数,这也是为什么我们需要在初始化```dp矩阵```时需要行列数均加上```1```***
用wikipedia上的伪码改造
```
function LevenshteinDistance(char s[1..m], char t[1..n]):
// for all i and j, d[i,j] will hold the Levenshtein distance between
// the first i characters of s and the first j characters of t
// note that d has (m+1)*(n+1) values
declare int d[0..m, 0..n]
set each element in d to zero
// source prefixes can be transformed into empty string by
// dropping all characters
for i from 1 to m:
d[i, 0] := i
// target prefixes can be reached from empty source prefix
// by inserting every character
for j from 1 to n:
d[0, j] := j
for j from 1 to n:
for i from 1 to m:
if s[i] = t[j]:
substitutionCost := 0
else:
substitutionCost := 1
d[i, j] := minimum(d[i-1, j] + 1, // deletion
d[i, j-1] + 1, // insertion
d[i-1, j-1] + substitutionCost) // substitution
return d[m, n]
```
对应的例子表格图
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册