题目
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
解题思路
按照pushed的顺序压栈,如果栈顶元素与popped的相同,则pop,最后判断是否所有元素都被pop完
代码
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
j, s, l = 0, [], len(popped)
for x in pushed:
s.append(x)
while s and s[-1] == popped[j]:
s.pop()
j += 1
return j == l