leecode第五百五十七题(反转字符串中的单词 III)

class Solution {
public:
    string reverseWords(string s) {
        string res;
        stack<char> sta;
        string::iterator iter = s.begin();
        
        while(iter<s.end())
        {
            if(*iter==' ')//如果遇到空格,就把栈内容弹到res中,然后补个空格
            {
                while(!sta.empty())
                {
                    res.push_back(sta.top());
                    sta.pop();
                }
                res.push_back(' ');
            }
            else//否则就压入栈中
                sta.push(*iter);
            
            iter++;
        }
        
        while(!sta.empty())//小心末尾没有空格的情况,补充一下
        {
            res.push_back(sta.top());
            sta.pop();
        }
        return res;
    }
};

分析:

在剑指offer上见过,一开始想依次检测单词,挨个翻转,但是想了想,好像有栈可以用,省时间。

自此leecode 50题里程碑达成,要暂时停下脚步反思了,最近只看老题,不做新题了~啦啦啦~

posted @ 2019-04-17 17:20  深夜十二点三十三  阅读(120)  评论(0编辑  收藏  举报