cpp: add «402. Remove K Digits»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-04-11 23:16:03 +02:00
parent 9101ade10b
commit 4a2d886d3f
Signed by: mfocko
GPG key ID: 7C47D46246790496

56
cpp/remove-k-digits.cpp Normal file
View file

@ -0,0 +1,56 @@
#include <algorithm>
#include <string>
#include <vector>
class Solution {
static bool nonZero(char c) { return c != '0'; }
public:
std::string removeKdigits(const std::string &num, int k) {
if (static_cast<int>(num.size()) <= k) {
return "0";
}
std::vector<char> digits;
for (auto d : num) {
while (k > 0 && !digits.empty() && d < digits.back()) {
--k;
digits.pop_back();
}
digits.push_back(d);
}
while (k-- > 0) {
digits.pop_back();
}
if (auto it = std::find_if(digits.begin(), digits.end(), nonZero);
it != digits.end()) {
return std::string(it, digits.end());
}
return "0";
}
};
#ifdef _MF_TEST
#include <gtest/gtest.h>
TEST(examples, no_1) {
Solution s;
EXPECT_EQ(s.removeKdigits("1432219", 3), "1219");
}
TEST(examples, no_2) {
Solution s;
EXPECT_EQ(s.removeKdigits("10200", 1), "200");
}
TEST(examples, no_3) {
Solution s;
EXPECT_EQ(s.removeKdigits("10", 2), "0");
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
#endif