题解 | #栈的压入、弹出序列#

栈的压入、弹出序列

https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106

#include <array>
#include <vector>
class Solution {
public:
    bool check(vector<int> in, vector<int> out) {
        if(in.size() != out.size()) return false;
        array<int, 2005> arr;
        for(auto x: in) {
            arr[x + 1000] = 1;
        }
        for(auto x: out) {
            if(--arr[x + 1000] != 0) return false;
        }
        return true;
    }
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        stack<int> stk;
        array<int, 2005> arr {};
        
        if(!check(pushV, popV)) return false;

        while(!popV.empty()) {
            //入栈
            while(stk.empty() || (stk.top() != popV.front() && !pushV.empty())) {
                if(arr[popV.front() + 1000]) return false;
                stk.push(pushV.front()); 
                arr[stk.top() + 1000] = 1;
                pushV.erase(pushV.cbegin());
            }
            if(stk.top() != popV.front() && arr[popV.front() + 1000]) return false;
            //出栈
            while(!stk.empty() && stk.top() == popV.front()) {
                //cout << stk.top() << " ";
                arr[stk.top() + 1000] = 0;
                stk.pop();
                popV.erase(popV.cbegin());
            }              
        }
        return true;
    }
};

全部评论

相关推荐

02-24 17:39
门头沟学院 Java
神哥不得了:神哥来啦~专业技能的话建议不要前面空那么多,八股的话建议先把高频top 50的八股多巩固几遍,千万不要看那些假高频八股。项目的话,建议换两个高质量的项目上去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务