Skip to content

Commit f9cade7

Browse files
committed
Create Reverse_Words_in_a_String.cc
1 parent 2bee2d6 commit f9cade7

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Reverse_Words_in_a_String.cc

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//O(1) space solution
2+
class Solution {
3+
public:
4+
void reverseWords(string &s) {
5+
preHandle(s);
6+
int left = 0, right;
7+
for (right = 0; right < s.length(); right++) {
8+
if (s[right] != ' ')
9+
continue;
10+
if (left < right - 1)
11+
reverse(s, left, right - 1);
12+
left = right + 1;
13+
}
14+
if (left < right - 1)
15+
reverse(s, left, right - 1);
16+
reverse(s, 0, right - 1);
17+
return;
18+
}
19+
private:
20+
void preHandle(string &s) {
21+
int slow = 0, fast = 0;
22+
while (slow < s.length()) {
23+
while (fast < s.length() && s[fast] == ' ')
24+
fast++;
25+
if (fast == s.length())
26+
break;
27+
if (slow != 0 && fast > 0 && s[fast - 1] == ' ')
28+
s[slow++] = ' ';
29+
s[slow++] = s[fast++];
30+
}
31+
s.resize(slow);
32+
}
33+
void reverse(string &s, int st, int ed) {
34+
char ch;
35+
while (st < ed) {
36+
ch = s[st];
37+
s[st] = s[ed];
38+
s[ed] = ch;
39+
st++, ed--;
40+
}
41+
}
42+
};

0 commit comments

Comments
 (0)