码迷,mamicode.com
首页 > 其他好文 > 详细

151. Reverse Words in a String

时间:2018-08-10 21:22:40      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:size   思路   class   note   between   red   strong   end   rds   

题目描述:

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

 

151. Reverse Words in a String

标签:size   思路   class   note   between   red   strong   end   rds   

原文地址:https://www.cnblogs.com/gsz-/p/9457126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!