|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the minimum distance (edit distance) recursively |
| 4 | + int solve(string word1, string word2, int i, int j) { |
| 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 | + int ans = 0; |
| 13 | + |
| 14 | + // If characters at the current positions match, move to the next character in both strings |
| 15 | + if (word1[i] == word2[j]) return solve(word1, word2, i + 1, j + 1); |
| 16 | + else { |
| 17 | + // If characters do not match, consider the three possible operations: |
| 18 | + // 1. Insert a character into word1 (move j ahead in word2) |
| 19 | + int insertAns = 1 + solve(word1, word2, i, j + 1); |
| 20 | + |
| 21 | + // 2. Delete a character from word1 (move i ahead in word1) |
| 22 | + int deleteAns = 1 + solve(word1, word2, i + 1, j); |
| 23 | + |
| 24 | + // 3. Replace a character in word1 (move both i and j ahead) |
| 25 | + int replaceAns = 1 + solve(word1, word2, i + 1, j + 1); |
| 26 | + |
| 27 | + // The minimum of these three options gives the optimal edit distance at this step |
| 28 | + ans = min({insertAns, deleteAns, replaceAns}); |
| 29 | + } |
| 30 | + |
| 31 | + // Return the minimum edit distance |
| 32 | + return ans; |
| 33 | + } |
| 34 | + |
| 35 | + // Main function that calculates the minimum distance between word1 and word2 |
| 36 | + int minDistance(string word1, string word2) { |
| 37 | + return solve(word1, word2, 0, 0); // Start the recursion from the beginning of both strings |
| 38 | + } |
| 39 | +}; |
0 commit comments