From 4d1e8d28d7ed617789b2b4ce0d1a3c5297e8caea Mon Sep 17 00:00:00 2001 From: Chunchi Che Date: Wed, 6 Mar 2024 19:10:47 +0800 Subject: [PATCH] Reverse words (#188) * add reverse words * impl reverse words * fix small --- leetcode-cc/ReverseWords.hpp | 56 ++++++++++++++++++++++++++++++++++ runtime-cc/src/registration.cc | 6 ++++ 2 files changed, 62 insertions(+) create mode 100644 leetcode-cc/ReverseWords.hpp diff --git a/leetcode-cc/ReverseWords.hpp b/leetcode-cc/ReverseWords.hpp new file mode 100644 index 0000000..0b3fe42 --- /dev/null +++ b/leetcode-cc/ReverseWords.hpp @@ -0,0 +1,56 @@ +#include + +#include "TestHelper.h" +#include "problem.h" +#include "solution.h" + +using namespace std; + +IMPLEMENT_PROBLEM_CLASS( + PReverseWords, 151, DIFFI_MEDIUM, TOPIC_ALGORITHMS, + "Reverse Words in a String", + "Given an input string s, reverse the order of the words.", {"Stack"}); + +class SReverseWords : public ISolution { + public: + size_t problemId() const override { return 151; } + string name() const override { + return ("Solution for " + string("Reverse Words in a String")); + } + string location() const override { return __FILE_NAME__; } + int test() const override { + return testHelper( + {"the sky is blue", " hello world ", "a good example"}, + {"blue is sky the", "world hello", "example good a"}, + [this](auto input) { return this->reverseWords(input); }); + }; + int benchmark() const override { return 0; } + + private: + string reverseWords(string s) const { + stack st = {}; + string current = ""; + + for (const auto& c : s) { + if (c == ' ') { + if (current != "") { + st.push(std::move(current)); + } + } else { + current += c; + } + } + + if (current != "") st.push(current); + + string res = ""; + while (!st.empty()) { + auto word = st.top(); + st.pop(); + res += word; + if (!st.empty()) res += " "; + } + + return res; + } +}; diff --git a/runtime-cc/src/registration.cc b/runtime-cc/src/registration.cc index c73a9fa..28cffba 100644 --- a/runtime-cc/src/registration.cc +++ b/runtime-cc/src/registration.cc @@ -71,6 +71,7 @@ #include "../leetcode-cc/RestoreIpAddresses.hpp" #include "../leetcode-cc/ReverseLinkedListII.hpp" #include "../leetcode-cc/ReverseNodesinKGroup.hpp" +#include "../leetcode-cc/ReverseWords.hpp" #include "../leetcode-cc/RomanToInteger.hpp" #include "../leetcode-cc/SameTree.hpp" #include "../leetcode-cc/ScrambleString.hpp" @@ -653,5 +654,10 @@ const int registerAll(std::shared_ptr handle) { handle->registerSolution( []() -> ArcSolution { return std::make_shared(); }); + handle->registerProblem( + []() -> ArcProblem { return std::make_shared(); }); + handle->registerSolution( + []() -> ArcSolution { return std::make_shared(); }); + return 0; }