Leetcode OJ : Reverse Words in a String

来源:互联网 发布:淘宝店铺装修助手 编辑:程序博客网 时间:2024/05/06 13:52

Given an input string, reverse the string word by word.

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

click to show clarification.

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;    }};


0 0