Cpp solution using stack


#1

string Solution::solve(string A) {
stack s;
string word;
int n = A.length();
for(int i=0; i<n; i++){
if(A[i]==’ ‘){
if(word!=""){
s.push(word);
}
word = “”;
} else {
word += A[i];
}
}
if(word!=""){
s.push(word);
}
if(s.empty())
return “”;
string ans;
string t = s.top();
for(char i: t)
ans.push_back(i);
s.pop();
while(!s.empty()){
ans.push_back(’ ');
string t = s.top();
for(char i: t)
ans.push_back(i);
s.pop();
}
return ans;
}