151. Reverse Words in a String

题目描述:

Example:  

Input: "the sky is blue",
Output: "blue is sky the".

Note:

  • A word is defined as a sequence of non-space characters.
  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up: For C programmers, try to solve it in-place in O(1) space.

解题思路:

题目不难,直接代码

代码:

 1 class Solution {
 2 public:
 3     void reverseWords(string &s) {
 4         reverse(s.begin(), s.end());
 5         istringstream sin(s);
 6         string word, res;
 7         while (sin>>word) {
 8             reverse(word.begin(), word.end());
 9             res += word;
10             res += " ";
11         }
12         if (res.size() > 0)
13             res.erase(res.size() - 1, 1);
14         s = res;
15     }
16 };

 

posted @ 2018-08-10 20:09  gszzsg  阅读(77)  评论(0编辑  收藏  举报