Skip to content

Commit 3801815

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent 8f46cf4 commit 3801815

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
public:
3+
// Helper function to calculate the minimum edit distance using dynamic programming
4+
int solve(string word1, string word2) {
5+
int n = word1.length(); // Length of the first string
6+
int m = word2.length(); // Length of the second string
7+
8+
// Create a dp table with dimensions (n+1) x (m+1), initialized to 0
9+
// dp[i][j] represents the minimum edit distance between word1[0..i-1] and word2[0..j-1]
10+
vector<vector<int>> dp(n+1, vector<int>(m+1, 0));
11+
12+
// Initialize the base cases for the last row and last column of the dp table
13+
for (int j = 0; j < m; j++) dp[n][j] = m - j; // If word1 is empty, we need to insert all characters from word2
14+
for (int i = 0; i < n; i++) dp[i][m] = n - i; // If word2 is empty, we need to delete all characters from word1
15+
16+
// Fill the dp table by processing the strings from bottom-right to top-left
17+
for (int i = n-1; i >= 0; i--) {
18+
for (int j = m-1; j >= 0; j--) {
19+
int ans = 0;
20+
21+
// If characters at current positions match, no operation is needed, take the result from the next diagonal cell
22+
if (word1[i] == word2[j]) {
23+
ans = dp[i+1][j+1];
24+
}
25+
else {
26+
// Otherwise, calculate the costs for insertion, deletion, and replacement:
27+
int insertAns = 1 + dp[i][j+1]; // Insert a character from word2 into word1 (move j ahead)
28+
int deleteAns = 1 + dp[i+1][j]; // Delete a character from word1 (move i ahead)
29+
int replaceAns = 1 + dp[i+1][j+1]; // Replace a character in word1 (move both i and j ahead)
30+
31+
// The minimum of these three options gives the optimal edit distance at this cell
32+
ans = min({insertAns, deleteAns, replaceAns});
33+
}
34+
35+
// Store the result in the dp table
36+
dp[i][j] = ans;
37+
}
38+
}
39+
40+
// The final result is stored in dp[0][0], which represents the minimum edit distance between word1 and word2
41+
return dp[0][0];
42+
}
43+
44+
// Main function that calculates the minimum distance between word1 and word2
45+
int minDistance(string word1, string word2) {
46+
return solve(word1, word2); // Call the solve function to compute the result
47+
}
48+
};

0 commit comments

Comments
 (0)