leetcode 946検証スタックシーケンス、pythonコード+構想
4414 ワード
"""
pushed popped , ,
push pop , true; , false 。
1:
:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
:true
: :
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
2:
:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
:false
:1 2 。
"""
'''
:
45321, 43512
12456 ,
32541 12345
:
1 3:1 - 2 - 3 - 3
2 2: 2
3 5: 4 - 5 - 5
4 4: 4
5 1: 1
!
43512 12345
:
1 4:1 - 2 - 3 - 4 - 4
2 3: 3
3 5: 5 - 5
4 1: 1 , 2
!
'''
class Solution:
def validateStackSequences(self, pushed, popped):
stack = []
for i in range(len(pushed)):
stack.append(pushed[i])
while stack and popped[0] == stack[-1]:
popped.pop(0)
stack.pop()
return len(stack) == 0
a = Solution().validateStackSequences([1, 2, 3, 4, 5], [4, 3, 5, 1, 2])
print(a)