"""
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列
是否为该栈的弹出序列。假设压入栈的所有数字均不相等。
"""
class Solution:
# 方法1
def IsPopOrder(self, pushV, popV):
if pushV == [] or popV == []:
return False
stack = []
for i in pushV:
stack.append(i)
if stack[-1] != popV[0]:
continue
else:
stack.pop()
popV.pop(0)
while len(stack) > 0 and stack[-1] == popV[0]:
stack.pop()
popV.pop(0)
if len(stack) == 0:
return True
else:
return False
# 方法2,进行了优化
def IsPopOrder2(self, pushV, popV):
if pushV == [] or popV == []:
return False
stack = []
for i in pushV:
stack.append(i)
while len(stack) and stack[-1] == popV[0]:
stack.pop()
popV.pop(0)
if len(stack):
return False
else:
return True
pushV = [1, 2, 3, 4, 5]
popV = [4, 5, 3, 2, 1]
popVF = [4, 5, 2, 1, 3]
S = Solution()
print(S.IsPopOrder(pushV, popVF))
剑指offer python版 31.栈的压入、弹出序列
最新推荐文章于 2022-03-23 15:32:34 发布