Reverse Words in a String

来源:互联网 发布:java 1.7 32位官网 编辑:程序博客网 时间:2024/04/29 20:01
Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

#include <iostream>#include <sstream>using namespace std;class Solution {public:void reverseWords(string &s) {istringstream istream(s);string word;stack<string> strStack;s.clear();bool first=true;while(istream>>word){strStack.push(word);}while(!strStack.empty()){word=strStack.top();strStack.pop();if(first){s.append(word);first = false;}else{s.append(" ");s.append(word);}}//cout<<s<<endl;}};

0 0
原创粉丝点击