剑指offer-21.栈的压入、弹出序列-Python

21.栈的压入、弹出序列

题目描述

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

记录

push和pop操作是混合使用的!!!
1,2,3,4,5
4,5,3,2,1

在这里插入图片描述
方法一:
利用辅助栈stack存从pushV中取出的数据;
[1,2,3,4] 4=4 [1,2,3] [5,3,2,1]
[1,2,3,5] 5=5 [1,2,3] [3,2,1]
3=3 [1,2] [1,2]
2=2 [1] [1]
1=1 [] []

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if not popV or not pushV:
            return False
        #辅助栈
        stack = []
        for i in pushV:
            stack.append(i)
            while stack and stack[-1] == popV[0]:
                stack.pop()
                popV.pop(0)
        #stack结束
        if not stack:
            return True
        else:
            return False

方法二
看的讨论。不使用辅助栈。
1,2,3,4,5
4,3,5,1,2
到[1,2] [1,2] i=1时,2!=1,i=2,i>=len(pushV):False

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if not popV or not pushV:
            return False
        i = 0
        for j in range(len(pushV)):
            while pushV[i] != popV[0]:
                i += 1
                if i>=len(pushV):
                    return False
            pushV.pop(i)
            popV.pop(0)
            i -= 1
        if not popV:
            return True
        else:
            return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值