File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments