class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if pushed is None or popped is None:
return False
if len(pushed) != len(popped):
return False
# index 指向popped数组,表示已经出栈的元素的下标,从0开始,一旦确认该元素出栈,index加一
index = 0
# 模拟栈操作创建的栈
stk = list()
for idx, item in enumerate(pushed):
# 不管如何 先放进栈中,完全模拟栈的操作
stk.append(item)
# 如果入栈的最后一个和出栈的元素相同,就进行出栈操作,
while stk and stk[-1] == popped[index]:
stk.pop()
index += 1
if len(stk) == 0:
return True
else:
return False
leetcode946 验证出栈顺序
最新推荐文章于 2023-01-08 17:40:17 发布