1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: string reverseWords(string s) { if(s.empty()) return ""; string ret = ""; int end = s.size() - 1; while(end >= 0 && s[end] == ' ') --end; if(end < 0) return ""; for(int i = end; i >= -1; --i) { if(i == -1 || s[i] == ' ') { ret.append(s.substr(i + 1, end - i)); while(i >= 0 && s[i] == ' ') --i; end = i; if(end < 0) break; ret.append(" "); } } return ret; } };
|