add: 220614

This commit is contained in:
Eat-Swap 2022-06-14 22:42:54 +08:00
parent 9c430083df
commit 1b7affe315
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 35 additions and 1 deletions

34
cpp/2206/220614.cpp Normal file
View File

@ -0,0 +1,34 @@
#include <string>
#include <cstring>
#include <iostream>
#include <functional>
/**
* 583. Delete Operation for Two Strings
* Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.
* In one step, you can delete exactly one character in either string.
*/
class Solution {
public:
static int minDistance(const std::string& word1, const std::string& word2) {
const int n1 = word1.length(), n2 = word2.length();
int dp[501][501];
std::memset(dp, -1, sizeof dp);
std::function<int(int, int)> d = [&](int i, int j) {
if (i < 0 || j < 0)
return 0;
if (dp[i][j] > 0)
return dp[i][j];
if (word1[i] == word2[j])
return dp[i][j] = 1 + d(i - 1, j - 1);
return dp[i][j] = std::max(d(i - 1, j), d(i, j - 1));
};
return n1 + n2 - (d(n1 - 1, n2 - 1) << 1);
}
};
int main() {
std::cout << Solution::minDistance("mart", "karma");
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2206)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2206 220614-CN.cpp) ADD_EXECUTABLE(2206 220614.cpp)