Skip to content

Commit

Permalink
Reverse words (#188)
Browse files Browse the repository at this point in the history
* add reverse words

* impl reverse words

* fix small
  • Loading branch information
SKTT1Ryze authored Mar 6, 2024
1 parent e952dc6 commit 4d1e8d2
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
56 changes: 56 additions & 0 deletions leetcode-cc/ReverseWords.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <stack>

#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<string, string>(
{"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<string> 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;
}
};
6 changes: 6 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -653,5 +654,10 @@ const int registerAll(std::shared_ptr<Container> handle) {
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SMaxPointsLine>(); });

handle->registerProblem(
[]() -> ArcProblem { return std::make_shared<PReverseWords>(); });
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SReverseWords>(); });

return 0;
}

0 comments on commit 4d1e8d2

Please sign in to comment.