-
Notifications
You must be signed in to change notification settings - Fork 0
/
JZ21.py
34 lines (29 loc) · 1.1 KB
/
JZ21.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding: utf-8 -*-
"""
@File :JZ21.py
@Author:Sapphire
@Date :2020/9/24 19:49
@Desc :栈的压入,弹出序列
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。
例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
(注意:这两个序列的长度是相等的)
"""
class Solution:
"""
attention:压入和弹出可以同时进行
使用压入序列,模拟栈的压入和弹出,从栈弹出序列的第一位开始匹配
"""
def IsPopOrder(self, pushV, popV):
# write code here
stackV = []
for i in pushV:
stackV.append(i)
while stackV and stackV[-1] == popV[0]:
stackV.pop()
del popV[0]
if stackV:
return False
else:
return True
solution = Solution()
print(solution.IsPopOrder([1, 2, 3, 4, 5], [4, 5, 3, 2, 1]))