Edit Distance
- Shreyas Naphad
- Jun 17, 2024
- 1 min read
Problem Statement: Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. We can use the following three operations on the string:
1. Insert a character.
2. Delete a character.
3. 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:
To solve this problem, we use dynamic programming. We define a 2D array dp where dp[i][j] represents the minimum number of operations required to convert the first i characters of word1 to the first j characters of word2.
Time Complexity: O(m x n)
Space Complexity: O(m x n)
コメント