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