-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution151.cpp
More file actions
54 lines (52 loc) · 998 Bytes
/
Copy pathsolution151.cpp
File metadata and controls
54 lines (52 loc) · 998 Bytes
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
/**
* Reverse Words in a String
*
* cpselvis(cpselvis@gmail.com)
* September 6th, 2016
*/
#include<iostream>
using namespace std;
class Solution {
public:
void reverseWords(string &s) {
stripSpaces(s);
reverse(s.begin(), s.end());
int i, j;
for (i = 0, j = 0; j < s.size(); j ++ )
{
if (s[j] == ' ')
{
reverse(s.begin() + i, s.begin() + j);
i = j + 1;
}
}
reverse(s.begin() + i, s.end());
}
void stripSpaces(string &s)
{
// Remove leading spaces before a string
while(s.size() > 0 && s[0] == ' ')
{
s.erase(0, 1);
}
s += ' ';
// Remove center space
for (int i = 0; i < s.size(); i ++)
{
while (s[i] == ' ' && s[i + 1] == ' ')
{
s.erase(i, 1);
}
}
// Remove last space
s.erase(s.size() - 1, 1);
}
};
int main(int argc, char **argv)
{
string str = " the sky is blue ";
// string str = "";
Solution s;
s.reverseWords(str);
cout << str << endl;
}