[LeetCode] Reverse Words in a String

151. Reverse Words in a String

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
private:
string subStringWhiteSpace(string s, int &pos, int start) {
int end = -1;
bool flag = true;
for(; pos >= start; pos--) {
if(s[pos] == ' ' && flag) continue;
if(s[pos] == ' ' && !flag) break;
if(end == -1) end = pos;
flag = false;
}

return s.substr(pos + 1, end - pos);
}
queue<string> reversedStringRemovedWitheSpace(string s) {
queue<string> q;
int pos = s.length() - 1, start;
for(start = 0; start < s.length() && s[start] == ' '; start++);

while(pos >= start) {
q.push(subStringWhiteSpace(s, pos, start));
}

return q;
}
public:
string reverseWords(string s) {
queue<string> q = reversedStringRemovedWitheSpace(s);

stringstream solution;

while(!q.empty()) {
solution<<q.front();
q.pop();
if(!q.empty())
solution<<' ';
}

return solution.str();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/16/PS/LeetCode/reverse-words-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.