Wins the offer - determine whether the correct stacks sequentially

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. 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)

Ideas:

With an empty stack, the stack to store the data

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        stack = []
        for num in popV:
            if num in pushV:
                for i in range(len(pushV)):
                    if pushV[i] == num:
                        break
                    else:
                        stack.append(pushV[i])
                pushV = pushV[i+1:]
            else:
                if len(stack)== 0:
                    return False
                if num!=stack[-1]:
                    return False
                else:
                    stack.pop()
        return True
            

 

Published 82 original articles · won praise 2 · Views 4366

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104745024