Skip to content

Commit 2466d4c

Browse files
authored
Create delete-operation-for-two-strings.cpp
1 parent b5ad85d commit 2466d4c

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Time: O(m * n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int minDistance(string word1, string word2) {
7+
const auto m = word1.length();
8+
const auto n = word2.length();
9+
10+
vector<vector<int>> dp(2, vector<int>(n + 1));
11+
for (int i = 0; i < m; ++i) {
12+
for (int j = 0; j < n; ++j) {
13+
dp[(i + 1) % 2][j + 1] = max(max(dp[i % 2][j + 1], dp[(i + 1) % 2][j]),
14+
dp[i % 2][j] + (word1[i] == word2[j]));
15+
}
16+
}
17+
return m + n - 2 * dp[m % 2][n];
18+
}
19+
};

0 commit comments

Comments
 (0)