Why does this code give the wrong output for the last word?


#1

string Solution::solve(string A) {
stacks;
string temp="";
for(int i=0;i<A.length();i++){
if(A[i]!=’ ‘)temp+=A[i];
else if(A[i]==’ ’ && temp!=""){
s.push(temp);
temp="";
}
else i++;
}
if(temp!="")s.push(temp);
string ans="";
if(s.size()>1){ans=s.top()+" “;
s.pop();}
while(!s.empty()){
if(s.size()>1)ans= ans+ s.top() +” ";
else
ans=ans+s.top();
s.pop();
}
return ans;
}