lc946.验证栈序列

 

题目链接

此题与jz031.栈的压入、弹出序列相同。这个算法的时间复杂度是O(N),空间复杂度是O(N)。

class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        stack, i = [], 0
        for num in pushed:
            stack.append(num)
            while stack and stack[-1] == popped[i]:
                stack.pop()
                i += 1
        return not stack