2023-02-26 Daily Challenge
Today I have done leetcode's February LeetCoding Challenge with cpp.
February LeetCoding Challenge 26
Description
Edit Distance
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
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')
Constraints:
0 <= word1.length, word2.length <= 500word1andword2consist of lowercase English letters.
Solution
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
class Solution {
public:
int minDistance(string word1, string word2) {
int dp[501][501];
int len1 = word1.length();
int len2 = word2.length();
for(int i = 0; i <= len1; ++i) {
dp[i][0] = i;
}
for(int j = 0; j <= len2; ++j) {
dp[0][j] = j;
}
for(int i = 0; i < len1; ++i) {
for(int j = 0; j < len2; ++j) {
dp[i + 1][j + 1] = min(dp[i][j + 1], dp[i + 1][j]) + 1;
if(word1[i] != word2[j]) dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + 1);
else dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j]);
cout << dp[i + 1][j + 1] << ' ';
}
cout << endl;
}
return dp[len1][len2];
}
};
// Accepted
// 1146/1146 cases passed (24 ms)
// Your runtime beats 27.06 % of cpp submissions
// Your memory usage beats 82.21 % of cpp submissions (7.2 MB)