剑指 Offer 58 - I. 翻转单词顺序

题目大意

RT

解题思路

主要是借这个题学习一下C++中的stringsteam的用法。

Code

  1. class Solution {
  2. public:
  3. string reverseWords(string s) {
  4. stack<string> st;
  5. stringstream ss;
  6. string ans = "";
  7. ss.str(s);
  8. string tmp;
  9. while (ss >> tmp) {
  10. st.push(tmp);
  11. }
  12. if (st.empty()) return ans;
  13. ans = st.top(); st.pop();
  14. while (!st.empty()) {
  15. ans.append(" ");
  16. ans.append(st.top()); st.pop();
  17. }
  18. return ans;
  19. }
  20. };