Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 reverseWords1(s); 5 } 6 7 void reverseWords1(string &s) { 8 istringstream is(s); 9 string word; 10 vector<string> vs; 11 while (is >> word) vs.push_back(word); 12 reverse(vs.begin(), vs.end()); 13 ostringstream os; 14 for (int i = 0; i < vs.size(); i++) { 15 if (i != 0) os << " "; 16 os << vs[i]; 17 } 18 s = os.str(); 19 } 20 21 void reverseWords2(string &s) { 22 string res; 23 int i = s.size() - 1; 24 while (i >= 0) { 25 while (i >= 0 && s[i] == ' ') i--; 26 if (i < 0) break; 27 string tmp; 28 while (i >= 0 && s[i] != ' ') tmp.push_back(s[i--]); 29 reverse(tmp.begin(), tmp.end()); 30 if (!res.empty()) res.push_back(' '); 31 res.append(tmp); 32 } 33 s = res; 34 } 35 };