[AlgoExpert] Reverse Words In String

Reverse Words In String

  • Time : O(n)
  • Space : O(n)
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
using namespace std;
string parse(string& s, int& p, bool space) {
string res = "";
while(p < s.length() and (s[p] == ' ') == space) {
res.push_back(s[p++]);
}
return res;
}
string reverseWordsInString(string str) {
if(str.length() == 0) return "";
vector<string> tokens;
int p = 0;
bool space = str[0] == ' ';
while(p < str.length()) {
tokens.push_back(parse(str, p, space));
tokens.push_back(parse(str, p, !space));
}
reverse(begin(tokens), end(tokens));
string res = "";
for(auto& t : tokens) {
res += t;
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/12/PS/AlgoExpert/reverse-words-in-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.