-
Notifications
You must be signed in to change notification settings - Fork 43
/
validate-stack-sequences.py
42 lines (40 loc) · 1.04 KB
/
validate-stack-sequences.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
34
35
36
37
38
39
40
41
42
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/84495797
class Solution(object):
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
stack = []
N = len(pushed)
pi = 0
for i in range(N):
if stack and popped[i] == stack[-1]:
stack.pop()
else:
while pi < N and pushed[pi] != popped[i]:
stack.append(pushed[pi])
pi += 1
pi += 1
return not stack
# V2
# Time: O(n)
# Space: O(n)
class Solution(object):
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
i = 0
s = []
for v in pushed:
s.append(v)
while s and i < len(popped) and s[-1] == popped[i]:
s.pop()
i += 1
return i == len(popped)