scan once, use stack
void reverseWords(string &s) {
stack<string> ret;
int start;
for(int i=0;i<s.length();i++){
if(s[i]==' ') continue;
start=i;
while(i<s.length()&&s[i]!=' ') i++;
ret.push(s.substr(start,i-start));
}
s="";
if(!ret.empty()){
s=ret.top();ret.pop();
}
while(!ret.empty()){
s=s+' '+ret.top();ret.pop();
}
}
No comments:
Post a Comment