-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreverseWords
More file actions
31 lines (30 loc) · 739 Bytes
/
reverseWords
File metadata and controls
31 lines (30 loc) · 739 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
class Solution {
public:
string reverseWords(string s) {
stack<string> st;
string ans, word;
int n = s.size();
for(int i=0; i<n; i++){
if(s[i] == ' ' && word.size() != 0){
st.push(word);
word = "";
}
else if(s[i] == ' ' && word.size() == 0){
continue;
}
else
word += s[i];
}
if(word.size() != 0){
st.push(word);
word = "";
}
while(!st.empty()){
string temp = st.top();
ans += temp + ' ';
st.pop();
}
ans.erase(ans.size()-1);
return ans;
}
};