0151.cpp (464B)
1 class Solution { 2 public: 3 string reverseWords(string s) { 4 string res = ""; 5 string buff = ""; 6 for (int i = 0; i < s.size(); i++) { 7 if (s[i] != ' ') { 8 buff += s[i]; 9 } else if (buff != "") { 10 res = buff + " " + res; 11 buff = ""; 12 } 13 } 14 if (buff != "") res = buff + " " + res; 15 if (res != "") res.pop_back(); 16 return res; 17 } 18 };