Reverse Left Words

This commit is contained in:
Sainnhe Park 2022-11-30 17:24:58 +08:00
parent 7b21a4bb3b
commit b13cfa00bb
5 changed files with 51 additions and 9 deletions

14
include/offer_58.hpp Normal file
View File

@ -0,0 +1,14 @@
#ifndef OFFER_58_HPP
#define OFFER_58_HPP
#include <string>
using namespace std;
class Solution {
public:
string reverseLeftWords(string s, int n);
void reverseSubStr(string &s, int begin, int end);
};
#endif

View File

@ -7,6 +7,7 @@ using namespace std;
class Solution {
public:
void reverseSubStr(string &s, int begin, int end);
string reverseWords(string s);
};

17
src/offer_58.cpp Normal file
View File

@ -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;
}

View File

@ -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;

19
tests/offer_58.cpp Normal file
View File

@ -0,0 +1,19 @@
#include "offer_58.hpp"
#include <gtest/gtest.h>
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);
}