# Code language: Python classSolution: defvalidateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: n = len(pushed) i, j = 0, 0 st = [] # 设置一个栈模拟出栈入栈行为 # 逐个检查能否得到popped出栈序列 while j < n: # 若栈顶元素不是当前popped序列所处理的那个或栈空,那就从pushed序列取元素入栈 while i < n and (not st or st[-1] != popped[j]): st.append(pushed[i]) i += 1 # 如果出栈序列用完了都得不到出栈序列元素,说明pushed的入栈顺序不可能得到popped的出栈顺序 ifnot i < n and st[-1] != popped[j]: returnFalse while st and j < n and st[-1] == popped[j]: st.pop() j += 1 returnTrue
# Code language: Python classSolution: # 模拟 + 空间优化 # 注意到我们设置用于模拟的栈大小不会超出pushed的大小,且pushed和popped的元素都只需遍历一次就行,那么我们可以在pushed上原地进行模拟,其余思路不变 defvalidateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: n = len(pushed) i, j = 0, 0 # pushed 已经遍历过的位置设置一个模拟栈的栈顶指针 s = 0 # 逐个检查能否得到popped出栈序列 while j < n: # 若栈顶元素不是当前popped序列所处理的那个或栈空,那就从pushed序列取元素入栈 while i < n and (s == 0or pushed[s - 1] != popped[j]): pushed[s] = pushed[i] s += 1 i += 1 # 如果出栈序列用完了都得不到出栈序列元素,说明pushed的入栈顺序不可能得到popped的出栈顺序 ifnot i < n and pushed[s - 1] != popped[j]: returnFalse while s > 0and j < n and pushed[s - 1] == popped[j]: s -= 1 j += 1 returnTrue