翻转字符串里的单词

题目链接:https://leetcode-cn.com/problems/reverse-words-in-a-string/
题目描述:

题解:

 class Solution {
  public:
    string reverseWords(string s) {
         stack <string> stk;
         string word = "";
         for(int i = 0; i < s.size(); i++)
         {
              if(s[i] != ' ')
             {
                 word += s[i];
                 if(s[i + 1] == ' ' || i == s.size() - 1) //如果该单词后为空格或该单词为最后一个单词
                 {
                     stk.push(word); //单词入栈
                     word = "";
                 }
             }
         }
         string str;
         while(!stk.empty())
         {
             str += stk.top();
             stk.pop();
             if(!stk.empty())  //最后一个单词后面不加空格
                 str += " ";
         }
         return str;
     }
 };

posted @ 2021-06-18 10:53  张宵  阅读(22)  评论(0编辑  收藏  举报