Reverse Words in a String

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.
经典的题目,注意题中的空格问题,首尾不能有空格,也不能有连续的空格
 1 class Solution {
 2 public:
 3     void trim(string &s){
 4       //去除首尾空格
 5       s.erase(s.begin(),find_if(s.begin(),s.end(),[](char c){return c!=' ';}));
 6       s.erase(find_if(s.rbegin(),s.rend(),[](char c){return c!=' ';}).base(),s.end());
 7       //去除重复空格
 8       s.erase(unique(s.begin(),s.end(),[](char l,char r){return l==r && l==' ';}),s.end());
 9     }
10     void reverseWords(string &s) {
11         std::reverse(s.begin(),s.end());
12         string::iterator wordBegin = s.begin();
13         while(wordBegin<s.end()){
14             string::iterator spaceIta =  find(wordBegin,s.end(),' ');
15             reverse(wordBegin,spaceIta);
16             wordBegin = spaceIta+1;
17         }
18         trim(s);
19     }
20 };

 


 

posted @ 2014-10-22 12:50  Madao_  阅读(126)  评论(0)    收藏  举报