0072. Edit Distance
Hard | String + DP | 88 ms (98.31%), 16.6 MB (84.05%)
Source: LeetCode - Edit Distance GitHub: Solution / Performance
Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three operations permitted on a word:
Insert a character
Delete a character
Replace a character
We simulate and figure out the cost of the following four operations:
Delete = 1 modification (Delete char in word1) Move to the next char in word1 to compare. So we take
table[i-1][j]
Insert = 1 modification (Insert char to word1) Move to the next char in word2 to compare. So we take
table[i][j-1]
Replace = 1 modification (Replace the char in word1) Move to the next char in both word1 and word2 to compare. So we take
table[i-1][j-1]
Skip = 0 modification (Two chars are the same) Move to the next char in both word1 and word2 to compare. So we take
table[i-1][j-1]
We create a 2D array and initialize values on table[i][0]
and table[0][j]
Then iterate through each char by the nested for loops to find the minimum operations.
i in range(1, len(word1) + 1)
j in range(1, len(word2) + 1)
Last updated
Was this helpful?