LeetCode: Reverse Words in a String
先来一个需要extra space的
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 vector<string> S; 5 int pre = 0; 6 string tmp = ""; 7 for (int i = 0; i < s.size(); ++i) { 8 if (isspace(s[i]) && tmp.size()) { 9 S.push_back(tmp); 10 tmp.clear(); 11 } 12 else if (!isspace(s[i])) tmp += s[i]; 13 } 14 if (tmp.size()) S.push_back(tmp); 15 s.clear(); 16 for (int i = S.size()-1; i >= 0; --i) { 17 if (i == S.size() - 1) s += S[i]; 18 else s = s + " " + S[i]; 19 } 20 } 21 };
再来个更好的
1 class Solution { 2 public: 3 void reverseWords(string &s) { 4 string rs; 5 for (int i = s.size()-1; i >= 0; ) { 6 while (i >= 0 && isspace(s[i])) i--; 7 if (i < 0) break; 8 if (rs.size()) rs += " "; 9 string t; 10 while(i >= 0 && !isspace(s[i])) t += s[i--]; 11 int left = 0; 12 int right = t.size()-1; 13 while (left < right) swap(t[left++], t[right--]); 14 rs += t; 15 } 16 s = rs; 17 } 18 };