[] 21. Offer wins the stack push, pop sequence implemented python

Title Description

Two input sequence of integers, the first sequence representing a pressed stack order, determines whether it is possible for the second sequence the order of the pop-up stack. All figures are not pushed onto the stack is assumed equal.
For example:
the sequence of a sequence of 1,2,3,4,5 is pressed into the stack, the push sequence is 4,5,3,2,1 sequence corresponding to a sequence of pop, but 4,3,5,1, 2 can not be a pop-up sequence of the push sequence. (Note: the length of the two sequences are equal)

Thinking

Pushed the order stack refers to 1,2,3,4,5 is in turn push to stack, but it does not mean that only push the process, there may pop operation, such as after a push 1,2,3,4, the 4pop out, then push5, is pressed into the same sequence; sequence refers pop pop out elements are each time element of the stack, such as a start push1,2,3,4, then POP4, then push5, then pop5, followed pop3,2,1, then the pop-up sequence is 4,5,3,2,1;

Then it can be configured to determine an auxiliary stack and a pop-up sequence is not push the corresponding sequences.
First traversal push element to push the auxiliary stack sequence, is determined not to eject the first sequence of elements, if so, the first element of the pop pop sequence (after the pointer moves), if not, continue to push, then it is then determined; down through the finished push sequence, if the auxiliary stack or pop-up sequence is empty, returns True, otherwise False

class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        stack = []
        for i in pushV:
            stack.append(i)
            while stack and stack[-1] == popV[0]:
                stack.pop()
                popV.pop(0)
        return True if not stack else False

if __name__ == '__main__':
    s = Solution()
    print(s.IsPopOrder([1,2,3,4,7,6], [3,6,7,4,2,1]))
Published 99 original articles · won praise 6 · views 3985

Guess you like

Origin blog.csdn.net/weixin_42247922/article/details/103958355