Skip to content

Commit a9f3290

Browse files
authored
Update Reverse Words in a String
1 parent 7f1453e commit a9f3290

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Top Interview 150/Reverse Words in a String

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,37 @@ public:
7373
return ans ;
7474
}
7575
};
76+
77+
78+
// 法三:先用 reverse 的技巧,並在 reverse 的過程中挑掉連續的空格,這樣就會得到一個單字內被 reverse,但順序正確的字串
79+
接著再把每個單字 reverse 回來即可
80+
81+
Time Complexity : O(n) for each character at most reverses two times
82+
Space Complexity : O(n) for the output string (沒有使用額外空間)
83+
84+
class Solution {
85+
public:
86+
string reverseWords(string s) {
87+
string ans ;
88+
int first = 0 ;
89+
while ( s[first] == ' ' )
90+
first++ ;
91+
92+
for(int i = s.length() - 1 ; i >= first ; i--) {
93+
if ( s[i] == ' ' && (i == s.length() - 1 || i == 0 || s[i + 1] == ' ') )
94+
continue ;
95+
ans += s[i] ;
96+
}
97+
98+
int start = 0 ;
99+
for(int i = 0 ; i < ans.length() ; i++) {
100+
if ( ans[i] == ' ' ) {
101+
reverse( ans.begin() + start , ans.begin() + i ) ;
102+
start = i + 1 ;
103+
}
104+
}
105+
reverse( ans.begin() + start , ans.end() ) ;
106+
107+
return ans ;
108+
}
109+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy