|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the minimum distance (edit distance) using recursion and memoization |
| 4 | + int solve(string word1, string word2, int i, int j, vector<vector<int>> &dp) { |
| 5 | + int n = word1.length(); // Length of the first string |
| 6 | + int m = word2.length(); // Length of the second string |
| 7 | + |
| 8 | + // Base cases: If one string is fully traversed, the remaining length of the other string is the answer |
| 9 | + if (i >= n) return m - j; // If word1 is fully traversed, we need to insert remaining characters of word2 |
| 10 | + if (j >= m) return n - i; // If word2 is fully traversed, we need to delete remaining characters of word1 |
| 11 | + |
| 12 | + // If the result for this subproblem is already computed (cached in dp table), return it |
| 13 | + if (dp[i][j] != -1) return dp[i][j]; |
| 14 | + |
| 15 | + int ans = 0; |
| 16 | + |
| 17 | + // If characters at the current positions match, move to the next character in both strings |
| 18 | + if (word1[i] == word2[j]) return solve(word1, word2, i + 1, j + 1, dp); |
| 19 | + else { |
| 20 | + // If characters do not match, consider the three possible operations: |
| 21 | + // 1. Insert a character into word1 (move j ahead in word2) |
| 22 | + int insertAns = 1 + solve(word1, word2, i, j + 1, dp); |
| 23 | + |
| 24 | + // 2. Delete a character from word1 (move i ahead in word1) |
| 25 | + int deleteAns = 1 + solve(word1, word2, i + 1, j, dp); |
| 26 | + |
| 27 | + // 3. Replace a character in word1 (move both i and j ahead) |
| 28 | + int replaceAns = 1 + solve(word1, word2, i + 1, j + 1, dp); |
| 29 | + |
| 30 | + // The minimum of these three options gives the optimal edit distance at this step |
| 31 | + ans = min({insertAns, deleteAns, replaceAns}); |
| 32 | + } |
| 33 | + |
| 34 | + // Store the computed result in the dp table and return it |
| 35 | + return dp[i][j] = ans; |
| 36 | + } |
| 37 | + |
| 38 | + // Main function that calculates the minimum distance between word1 and word2 |
| 39 | + int minDistance(string word1, string word2) { |
| 40 | + // Create a dp table initialized to -1 (indicating that no subproblem has been solved yet) |
| 41 | + // dp[i][j] represents the minimum edit distance between word1[0..i-1] and word2[0..j-1] |
| 42 | + vector<vector<int>> dp(word1.length() + 1, vector<int>(word2.length() + 1, -1)); |
| 43 | + |
| 44 | + // Call the solve function starting from the beginning of both strings |
| 45 | + return solve(word1, word2, 0, 0, dp); |
| 46 | + } |
| 47 | +}; |
0 commit comments