思路
方法:分割 + 倒序
时间复杂度:O(n),n为s的长度。
1 class Solution { 2 public: 3 string reverseWords(string s) { 4 string t = ""; 5 stack<string> strStack; 6 for(int i = 0; i < s.length(); ++i) { 7 if(s[i] == ' ') { 8 if(t != "") { 9 strStack.push(t); 10 t = ""; 11 } 12 } else { 13 t.push_back(s[i]); 14 } 15 } 16 17 if(t != "") 18 strStack.push(t); 19 20 t = ""; 21 while(!strStack.empty()) { 22 t += strStack.top(); 23 if(strStack.size() > 1) { 24 t.push_back(' '); 25 } 26 27 strStack.pop(); 28 } 29 30 return t; 31 } 32 };