python stack 判斷出棧順序
阿新 • • 發佈:2018-12-10
LeetCode 946 Validate Stack Sequences
思想:迴圈判斷進棧序列,當進棧序列的值沒有遇到與出棧序列相同時壓棧,迴圈當棧不為空並且出棧序列的第一個值等於棧頂元素時出棧,出棧指標後移,若棧空則序列正確
class Solution(object): def validateStackSequences(self, pushed, popped): """ :type pushed: List[int] :type popped: List[int] :rtype: bool """ stack=[] num=len(pushed) p=0 for x in pushed: stack.append(x) while stack and (stack[-1]==popped[p]): stack.pop() p=p+1 return not len(stack)