【剑指offer】栈的压入、弹出序列

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列 1 , 2 , 3 , 4 , 5 1,2,3,4,5 1,2,3,4,5是某栈的压入顺序,序列 4 , 5 , 3 , 2 , 1 4,5,3,2,1 4,5,3,2,1是该压栈序列对应的一个弹出序列,但 4 , 3 , 5 , 1 , 2 4,3,5,1,2 4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路:建一个辅助栈,然后按照入栈的顺序进行入栈,在入栈过程中判断当前值是否与出栈序列元素值相等,相等则将其出栈,待所有元素入栈后,判断辅助栈是否为空,如果为空则说明该出栈序列是压栈序列的一个弹出序列

略显复杂的版本,不过思想是一致的:

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        if (pushV.size() != popV.size())
            return false;
        bool bPossible = false;
        if (!pushV.empty() && !popV.empty()) {
            vector<int>::iterator itPush = pushV.begin();
            vector<int>::iterator itPop = popV.begin();
            stack<int> stackdata;
            while (itPop != popV.end()) {
                while (stackdata.empty() || stackdata.top() != *itPop) {
                    if (itPush == pushV.end()) {
                        break;
                    }
                    stackdata.push(*itPush);
                    itPush++;
                }
                if (stackdata.top() != *itPop)
                    break;
                stackdata.pop();
                itPop++;
            }
            if (stackdata.empty() && itPop == popV.end())
                bPossible = true;
        }
        return bPossible;
    }
};

比较简洁的版本:

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        if (pushV.size() == 0)
            return false;
        stack<int> s;
        int j = 0;
        for (int i = 0;i < pushV.size(); ++i) {
            s.push(pushV[i]);
            while (!s.empty() && j < popV.size() && s.top() == popV[j]) {
                s.pop();
                ++j;
            }
        }
        return s.empty();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值