From b13cfa00bb817fb28f4014efaa2b0101bb8eab7f Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Wed, 30 Nov 2022 17:24:58 +0800 Subject: [PATCH] Reverse Left Words --- include/offer_58.hpp | 14 ++++++++++++++ include/s0151_reverse_words_in_a_string.hpp | 1 + src/offer_58.cpp | 17 +++++++++++++++++ src/s0151_reverse_words_in_a_string.cpp | 9 --------- tests/offer_58.cpp | 19 +++++++++++++++++++ 5 files changed, 51 insertions(+), 9 deletions(-) create mode 100644 include/offer_58.hpp create mode 100644 src/offer_58.cpp create mode 100644 tests/offer_58.cpp diff --git a/include/offer_58.hpp b/include/offer_58.hpp new file mode 100644 index 0000000..5817f4b --- /dev/null +++ b/include/offer_58.hpp @@ -0,0 +1,14 @@ +#ifndef OFFER_58_HPP +#define OFFER_58_HPP + +#include + +using namespace std; + +class Solution { + public: + string reverseLeftWords(string s, int n); + void reverseSubStr(string &s, int begin, int end); +}; + +#endif diff --git a/include/s0151_reverse_words_in_a_string.hpp b/include/s0151_reverse_words_in_a_string.hpp index c8e4977..e0dd25d 100644 --- a/include/s0151_reverse_words_in_a_string.hpp +++ b/include/s0151_reverse_words_in_a_string.hpp @@ -7,6 +7,7 @@ using namespace std; class Solution { public: + void reverseSubStr(string &s, int begin, int end); string reverseWords(string s); }; diff --git a/src/offer_58.cpp b/src/offer_58.cpp new file mode 100644 index 0000000..4a79a4b --- /dev/null +++ b/src/offer_58.cpp @@ -0,0 +1,17 @@ +#include "offer_58.hpp" + +void Solution::reverseSubStr(string &s, int begin, int end) { + for (; begin < end; ++begin, --end) { + char tmp = s[begin]; + s[begin] = s[end]; + s[end] = tmp; + } +} + +string Solution::reverseLeftWords(string s, int n) { + int len = s.length(); + reverseSubStr(s, 0, n - 1); + reverseSubStr(s, n, len - 1); + reverseSubStr(s, 0, len - 1); + return s; +} diff --git a/src/s0151_reverse_words_in_a_string.cpp b/src/s0151_reverse_words_in_a_string.cpp index 29082e2..a224a51 100644 --- a/src/s0151_reverse_words_in_a_string.cpp +++ b/src/s0151_reverse_words_in_a_string.cpp @@ -1,14 +1,5 @@ #include "s0151_reverse_words_in_a_string.hpp" -// reverse a substring -void reverseSubStr(string &s, int begin, int end) { - for (; begin < end; ++begin, --end) { - auto tmp = s[begin]; - s[begin] = s[end]; - s[end] = tmp; - } -} - string Solution::reverseWords(string s) { if (s.length() == 0) { return s; diff --git a/tests/offer_58.cpp b/tests/offer_58.cpp new file mode 100644 index 0000000..d86ee3b --- /dev/null +++ b/tests/offer_58.cpp @@ -0,0 +1,19 @@ +#include "offer_58.hpp" + +#include + +TEST(Offer58, Case1) { + string s{"abcdefg"}; + int k{2}; + string expected{"cdefgab"}; + Solution solution; + EXPECT_EQ(solution.reverseLeftWords(s, k), expected); +} + +TEST(Offer58, Case2) { + string s{"lrloseumgh"}; + int k{6}; + string expected{"umghlrlose"}; + Solution solution; + EXPECT_EQ(solution.reverseLeftWords(s, k), expected); +}