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
".
题目地址:https://oj.leetcode.com/problems/reverse-words-in-a-string/
算法:先把字符串分成一个一个word放在vector里面,然后在按逆序存入原来的字符串里。代码:
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 vector<string> words = split(s); 5 s.clear(); 6 vector<string>::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<string> split(const string &s){ 17 string t; 18 vector<string> 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 };