Reverse Words in a String

This commit is contained in:
Sainnhe Park 2022-11-30 16:24:38 +08:00
parent e37f2531d7
commit 8a54f4a29b
5 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,13 @@
#ifndef S0151_REVERSE_WORDS_IN_A_STRING_HPP
#define S0151_REVERSE_WORDS_IN_A_STRING_HPP
#include <string>
using namespace std;
class Solution {
public:
string reverseWords(string s);
};
#endif

View File

@ -7,6 +7,7 @@
# 字符串 # 字符串
- [替换空格](./substitute_spaces.md) - [替换空格](./substitute_spaces.md)
- [翻转字符串里的单词](./reverse_words_in_a_string.md)
# 经典代码 # 经典代码

View File

@ -0,0 +1,27 @@
# 翻转字符串里的单词
[Leetcode](https://leetcode.com/problems/reverse-words-in-a-string/)
1. 去除单词中的额外空格
2. 翻转整个字符串
3. 挨个翻转单词
双指针去除额外空格:
如果快指针指向的是空格则跳过;
如果快指针指向的不是空格则把 `s[fast]` 覆盖到 `s[slow]`
如果快指针指向的是空格并且下一个指向的不是空格,则在 `s[slow]` 处添加一个新空格(前提是 `slow` 不为 `0`,因为这种情况代表字符串的开头是空格)。
翻转字符串:
```cpp
void reverseSubStr(string &s, int begin, int end) {
for (; begin < end; ++begin, --end) {
auto tmp = s[begin];
s[begin] = s[end];
s[end] = tmp;
}
}
```

View File

@ -0,0 +1,49 @@
#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;
}
// remove extra spaces
int len = s.length();
int slow{0};
for (int fast{0}; fast < len; ++fast) {
if (s[fast] != ' ') {
s[slow++] = s[fast];
} else {
if (fast == len - 1) {
break;
} else {
if (s[fast + 1] != ' ' && slow != 0) {
s[slow++] = ' ';
}
}
}
}
s.resize(slow);
// reverse the whole string
len = s.length();
reverseSubStr(s, 0, len - 1);
// reverse each words
for (int begin{0}, end{0}; end < len; ++end) {
if (end == len - 1) {
reverseSubStr(s, begin, end);
} else {
if (s[end + 1] == ' ') {
reverseSubStr(s, begin, end);
begin = end + 2;
end = end + 1;
}
}
}
return s;
}

View File

@ -0,0 +1,31 @@
#include "s0151_reverse_words_in_a_string.hpp"
#include <gtest/gtest.h>
TEST(Problem151, Case1) {
string s{"the sky is blue"};
string expected{"blue is sky the"};
Solution solution;
EXPECT_EQ(solution.reverseWords(s), expected);
}
TEST(Problem151, Case2) {
string s{" hello world "};
string expected{"world hello"};
Solution solution;
EXPECT_EQ(solution.reverseWords(s), expected);
}
TEST(Problem151, Case3) {
string s{"a good example"};
string expected{"example good a"};
Solution solution;
EXPECT_EQ(solution.reverseWords(s), expected);
}
TEST(Problem151, Case4) {
string s{"F R I E N D S "};
string expected{"S D N E I R F"};
Solution solution;
EXPECT_EQ(solution.reverseWords(s), expected);
}