-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverseWord.cpp
55 lines (48 loc) · 970 Bytes
/
reverseWord.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* Given an input string, reverse the string word by word.
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
*
*
*/
/*
*
*
*
*/
#include <iostream>
#include <climits>
#include <algorithm>
#include <vector>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <queue>
#include <list>
class Solution {
public:
void reverseWords(std::string &s) {
int i = 0, j = 0;
int l = 0;
int len = s.length();
int wc = 0;
while (true) {
while (i < len && s[i] == ' ') i++;
if (i == len) break;
if (wc) s[j++] = ' ';
l = j;
while (i < len && s[i] != ' ') s[j++] = s[i++];
std::reverse(s.begin() + l, s.begin() + j);
wc++;
}
s.resize(j);
std::reverse(s.begin(), s.begin() + j);
}
};
int main() {
Solution solute;
std::string s = "the sky is blue";
solute.reverseWords(s);
std::cout << s << std::endl;
}