From 4a2d886d3f677c4098c0ba0a80ccc01784062e36 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 11 Apr 2024 23:16:03 +0200 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB402.=20Remove=20K=20Digits?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/remove-k-digits.cpp | 56 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 cpp/remove-k-digits.cpp diff --git a/cpp/remove-k-digits.cpp b/cpp/remove-k-digits.cpp new file mode 100644 index 0000000..52358bb --- /dev/null +++ b/cpp/remove-k-digits.cpp @@ -0,0 +1,56 @@ +#include +#include +#include + +class Solution { + static bool nonZero(char c) { return c != '0'; } + + public: + std::string removeKdigits(const std::string &num, int k) { + if (static_cast(num.size()) <= k) { + return "0"; + } + + std::vector 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 + +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