add: 220218 [C++]

This commit is contained in:
Lam Haoyin 2022-02-19 00:41:26 +08:00
parent 8753504ee4
commit 711bb11ecc
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 26 additions and 1 deletions

25
2202/220218.cpp Normal file
View File

@ -0,0 +1,25 @@
#include <string>
#include <vector>
#include <iostream>
class Solution {
public:
static std::string removeKdigits(const std::string& num, int k) {
std::vector<char> stack;
stack.reserve(num.length() - k);
for (char ch : num) {
while (k && !stack.empty() && stack.back() > ch) {
stack.pop_back();
--k;
}
stack.push_back(ch);
}
std::string ret(stack.begin(), k > 0 ? std::prev(stack.end(), k) : stack.end());
return ret.empty() || ret.find_first_not_of('0') == -1 ? "0" : ret.substr(ret.find_first_not_of('0'));
}
};
int main() {
std::cout << Solution::removeKdigits("1432219", 3);
return 0;
}

View File

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