LeetCode 72. 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')
Solution
设最短距离方法为f
:
反推:
f("horse", "ros") = 1 + min(f("hors", "ros"), // 删除 hors[e]
f("horse", "ro"), // 插入 ro[s]
f("hors", "ro")) // 替换 hors[e] ro[s]
f("hors", "ros") = 1 + min(f("hor", "ros"), // 删除 hor[s]
f("hors", "ro"), // 插入 ro[s]
f("hor", "ro")) // 替换 hor[s] ro[s]
...
特殊情况和边界条件:
如果最后一个字符相同,则不用操作,distance = 0
如果其中一个字符串为空,则 distance = 另一个字符串长度
解释:
- 删除
hors[e]
:通过f("hors", "ros")
将hors
变成ros
,则有rose
删除最后一位得到ros
- 插入
ro[s]
:通过f("horse", "ro")
将horse
变成ro
,则插入一位s
得到ros
- 替换
替换 hors[e] ro[s]
:通过f("hors", "ro")
将hors
变成ro
,则有roe
替换最后一位得到ros
递归(Recursive)
|
|
动态规划(Dynamic Programming)
|
|