Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7f1453e

Browse files
Update Reverse Words in a String
1 parent 142637c commit 7f1453e

File tree

1 file changed

+18
-18
lines changed

1 file changed

+18
-18
lines changed

‎Top Interview 150/Reverse Words in a String

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -45,30 +45,30 @@ Space Complexity : O(n) for the answer string
4545
class Solution {
4646
public:
4747
string reverseWords(string s) {
48-
stack<string> store ;
48+
string ans ;
4949
string temp ;
50-
for(auto &i : s) {
51-
if ( i == ' ' ) {
50+
for(auto &c : s) {
51+
if ( c == ' ' ) {
5252
if ( !temp.empty() ) {
53-
store.push(temp) ;
54-
temp = "";
53+
if ( ans.empty() )
54+
ans = temp ;
55+
else
56+
ans = temp + " " + ans ;
57+
58+
temp = "" ;
5559
}
5660
}
5761
else
58-
temp += i ;
59-
}
60-
if (!temp.empty())
61-
store.push(temp);
62+
temp += c ;
6263

63-
string ans ;
64-
while ( !store.empty() ) {
65-
if ( ans.empty() ) {
66-
ans += store.top() ;
67-
}
68-
else {
69-
ans += " " + store.top() ;
70-
}
71-
store.pop() ;
64+
}
65+
if ( !temp.empty() ) {
66+
if ( ans.empty() )
67+
ans = temp ;
68+
else
69+
ans = temp + " " + ans ;
70+
71+
temp = "" ;
7272
}
7373
return ans ;
7474
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /