Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
这一题和PAT里的那个题目基本是一样的,
http://blog.csdn.net/xiaqunfeng123/article/details/19989735
代码如下:
class Solution
{
public:
void reverseWords(string &s)
{
stack<string> str;
string word,temp;
bool flag=false;
stringstream ss(s);
while(ss>>word)
str.push(word);
while(!str.empty())
{
if(flag)
temp+=" ";
else
flag=true;
temp+=str.top();
str.pop();
}
s=temp;
}
};