while (!st.empty()) { tmp = st.top(); st.pop(); res += tmp; res += " "; } res.pop_back(); // Remove the last space return res; } };
Two pointers
You can also use two pointers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: string reverseWords(string s){ // Use two pointers int m = s.size() - 1; string res; // Remove trailing spaces while (s[m] == ' ' && m > 0) m--; int n = m; // n is another pointer while (m >= 0) { while (m >= 0 && s[m] != ' ') m--; res += s.substr(m + 1, n - m) + " "; // Get the word and add a space while (m >= 0 && s[m] == ' ') m--; n = m; } return res.substr(0, res.size() - 1); // ignore the trailing space } };