From 2a35c97936dfcae4ed1352c8753f1497a8e9b51f Mon Sep 17 00:00:00 2001 From: Ace-Krypton Date: Sun, 1 Oct 2023 15:47:07 +0200 Subject: [PATCH] Added Reverse Words in a String III --- CMakeLists.txt | 11 +++++++ .../include/solution.hpp | 23 +++++++++++++++ Easy/ReverseWordsInAStringIII/tests/test.cpp | 29 +++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 Easy/ReverseWordsInAStringIII/include/solution.hpp create mode 100644 Easy/ReverseWordsInAStringIII/tests/test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d46fce..5019040 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1173,4 +1173,15 @@ add_executable(EqualRowAndColumnPairs target_link_libraries( EqualRowAndColumnPairs GTest::gtest_main +) + +# Reverse Words in a String III +add_executable(ReverseWordsInAStringIII + Easy/ReverseWordsInAStringIII/include/solution.hpp + Easy/ReverseWordsInAStringIII/tests/test.cpp +) + +target_link_libraries( + ReverseWordsInAStringIII + GTest::gtest_main ) \ No newline at end of file diff --git a/Easy/ReverseWordsInAStringIII/include/solution.hpp b/Easy/ReverseWordsInAStringIII/include/solution.hpp new file mode 100644 index 0000000..3607944 --- /dev/null +++ b/Easy/ReverseWordsInAStringIII/include/solution.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include +#include +#include +#include + +class Solution { +public: + static auto reverse_words(std::string &word) -> std::string { + std::stringstream ss(word); + std::string result; + + while (ss >> word) { + std::string reversed_word(word.rbegin(), word.rend()); + result += reversed_word + " "; + } + + if (!result.empty()) result.pop_back(); + + return result; + } +}; diff --git a/Easy/ReverseWordsInAStringIII/tests/test.cpp b/Easy/ReverseWordsInAStringIII/tests/test.cpp new file mode 100644 index 0000000..6469efa --- /dev/null +++ b/Easy/ReverseWordsInAStringIII/tests/test.cpp @@ -0,0 +1,29 @@ +#include "../include/solution.hpp" + +class ReverseWordsInAStringIII : public ::testing::Test { +protected: + ~ReverseWordsInAStringIII() override = default; +}; + +TEST_F(ReverseWordsInAStringIII, FirstTest) { + std::string word = "Let's take LeetCode contest"; + + std::string result = Solution::reverse_words(word); + std::string expected = "s'teL ekat edoCteeL tsetnoc"; + + ASSERT_EQ(result, expected); +} + +TEST_F(ReverseWordsInAStringIII, SecondTest) { + std::string word = "God Ding"; + + std::string result = Solution::reverse_words(word); + std::string expected = "doG gniD"; + + ASSERT_EQ(result, expected); +} + +auto main(int argc, char **argv) -> int { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}