LeetCode: 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
".
题目地址:
算法:先把字符串分成一个一个word放在vector里面,然后在按逆序存入原来的字符串里。代码:
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 vectorwords = split(s); 5 s.clear(); 6 vector ::reverse_iterator iter = words.rbegin(); 7 if(iter != words.rend()){ 8 s += *iter; 9 ++iter;10 }11 for(; iter != words.rend(); ++iter){12 s += " ";13 s += *iter;14 }15 }16 vector split(const string &s){17 string t;18 vector words;19 string::const_iterator p = s.begin();20 while(p != s.end()){21 while(p != s.end() && isspace(*p)){22 ++p;23 }24 while(p != s.end() && !isspace(*p)){25 t.push_back(*p);26 ++p;27 }28 if(!t.empty()){29 words.push_back(t);30 t.clear();31 }32 }33 return words;34 }35 };
posted on 2014-07-27 21:07 阅读( ...) 评论( ...)