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’)
|
|
Solution
设最短距离方法为f
:
|
|
解释:
- 删除
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)
|
|