剑指offer31 栈的压入、弹出序列

剑指offer31 栈的压入、弹出序列

     输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。

     假设压入栈的所有数字均不相等。

     例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。

     注意:若两个序列长度不等则视为并不是一个栈的压入、弹出序列。若两个序列都为空,则视为是一个栈的压入、弹出序列。

样例

输入:[1,2,3,4,5]
      [4,5,3,2,1]

输出:true

思路

     用一个栈去模拟,把进栈队列依次入站,然后碰到出栈队列则出栈,最后判断栈是否为空以及进栈队列是否都已进栈,出栈队列是否都出栈。

AcWing-42 c++ code

class Solution {
public:
    bool isPopOrder(vector<int> pushV,vector<int> popV) {
        if(pushV.size() != popV.size()){
            return false;
        }
        int n = pushV.size();
        stack<int> nums;
        int indexPop = 0;
        for(int i = 0; i < n; i++){
            nums.push(pushV[i]);
            while(!nums.empty() && nums.top() == popV[indexPop]){
                nums.pop();
                indexPop++;
            }
        }
        if(indexPop == n){
            return true;
        }else{
            return false;
        }
    }
};

AcWing-42 python code

class Solution(object):
    def isPopOrder(self, pushV, popV):
        """
        :type pushV: list[int]
        :type popV: list[int]
        :rtype: bool
        """
        if len(pushV) != len(popV):
            return False
        elif len(pushV) == len(popV) ==0:
            return True
        s = []
        pushV_id = 0;
        popV_id = 0;
        n = len(pushV)
        while pushV_id < n:
            s.append(pushV[pushV_id])
            pushV_id += 1
            
            while len(s) != 0 and popV_id < n and s[-1] == popV[popV_id]:
                s.pop()
                popV_id += 1
            
        if popV_id < n:
            return False
        else:
            return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值