Problem
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:
1 |
|
Example 2:
1 |
|
Explanation
-
We can use dynamic programming to solve this problem. For example, word1 = “12b45”, word2 = “abcde”. We can draw a dynamic table like below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16word2 empty a b c d e word1 +----------------------------------+ | empty | 0 1 2 3 4 5 | 1 | 1 1 2 3 | 2 | 2 2 2 3 | b | 3 3 2 3 | 4 | 4 4 3 3 | 5 | 5 +
-
State is
dp[r][c]
, which represents the minimum operation to convertword1[0, r-1]
toword2[0, c-1]
. -
Init is when word1 is empty (top row), if word2 is also empty, then there are 0 operation to convert word1 to word2; if word2 has length 1, then there are 1 insert operation to convert word1 to word2; if word2 has length 2, then there are 2 insert operations to convert word1 to word2; if word3 has length 3, then we need 3 insert operations, etc.
-
When word2 is empty (left most column), if word1 is also empty, then there are we need 0 operation; if word1 has length 1, then we need 1 remove operation; if word1 has length 2, then we need 2 remove operation, etc.
-
Dynamic function is if the last character of both words are the same, for example, word1 = “12b”, word2 = “ab”, then the number of operations we need is the same as comparing word1 = “12” and word2 = “a”. In other words, if the last characters of both words are the same, then
dp[r][c] = dp[r-1][c-1]
. -
If the last character of both words are not the same, for example, word1 = “12b4”, word2 = “abc”, then we need to consider three cases:
-
Delete “4” from word1, then compare word1 = “12b” and word2 = “abc”. In other word,
dp[r][c] = 1 + dp[r-1][c]
. -
Replace “4” with “c”, then compare word1 = “12b” and word2 = “ab”. In other word,
dp[r][c] = 1 + dp[r-1][c-1]
. -
Insert “c” at the end of word1, then compare word1 = “12b4” and word2 = “ab”. In other word,
dp[r][c] = 1 + dp[r][c-1]
.
-
-
If the last character of both words are not the same, we should take the minimum among these 3 operations as the result of
dp[r][c]
. -
Dynamic result is
dp[len(word1)][len(word2)]
which is at the bottom right.
Solution
1 |
|