Old Wei wins the offer to take you to learn --- Brush title series (21 stack push, pop sequence)

21. The stack push, pop sequence

problem:

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. Such as a 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 it is impossible to push pop-up sequence of the sequence. (Note: the length of the two sequences are equal)

solve:

thought:

Borrow an auxiliary stack, push traversal order, into a first talk about the stack, here 1, is determined and then the top element is not out of the first element stack order, this is 4, it is clear that a ≠ 4 so we continue to push until after the start of an equal stack, the stack is an element, it will move back one, until the order is not equal to the stack, and so the cycle Yazhan order traversal is complete, if the auxiliary stack is not empty described sequence is not the sequence of pop pop stack.

For example:

Drawing 1,2,3,4,5

Stack 4,5,3,2,1

1 into the first auxiliary stack, when the stack 1 ≠ 4, continued stack 2

At this time, the stack 2 ≠ 4, continue to stack 3

At this time, the stack 3 ≠ 4, 4 continue to stack

At this time, the stack 4 = 4, the stack 4, a pop-up sequence back, in this case the auxiliary stack 5 inside 1,2,3 ,,

At this time, the stack 3 ≠ 5, 5 continue to push

5 = At ​​this point the stack 5, the stack 5, a pop-up sequence back, in this case the auxiliary stack 3 which is 2,3 ,,

….

Followed by the implementation, and finally the auxiliary stack is empty. If not empty pop-described sequence is not the sequence of pop stack.

python code:

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if not pushV or len(pushV)!=len(popV):
            return False
        stack=[]
        for i in pushV:
            stack.append(i)
            while(len(stack) and stack[-1]==popV[0]):
                stack.pop()
                popV.pop(0)
        if(len(stack)):
            return False
        return True
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/104921036