输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
这道题卡了很久都不知道是什么意思。
下面结合代码讲解一下。
看弹出序列4 5321,说明最后一个弹出的是4,在压入顺序中为第四位
那么第三个压入的是3或者弹出5,看看弹出序列有没有5,有。再看看弹出序列现在栈顶为3,说明接下是压入了3,弹出序列有3。同理直到为零。
看看代码实现,以及辅助栈是怎么样的。
def IsPopOrder(pushV, popV):
if not pushV or len(pushV)!=len(popV):
return 0
stack=[]
for i in pushV:
stack.append(i)
print("stack",stack)
while len(stack) and stack[-1]==popV[0]:
stack.pop()
print("stack after:",stack)
popV.pop(0)
print("popV after:",popV)
if len(stack):
return 0
return 1
n=[1,2,3,4,5]
l=[4,5,3,1,2]
'out' :
stack [1]
stack [1, 2]
stack [1, 2, 3]
stack [1, 2, 3, 4]
stack after: [1, 2, 3]
popV after: [5, 3, 1, 2]
stack [1, 2, 3, 5]
stack after: [1, 2, 3]
popV after: [3, 1, 2]
stack after: [1, 2]
popV after: [1, 2]