The sword refers to offer: the push and pop sequence of the stack (python)

Topic description

Input two integer sequences. The first sequence represents the stack's push sequence. Please check whether the second sequence is the stack's pop-up sequence. Assume that all numbers pushed onto the stack are not equal. For example, the sequence 1, 2, 3, 4, 5 is the push sequence of a stack, the sequence 4, 5, 3, 2, 1 is a pop sequence corresponding to the stack sequence, but 4, 3, 5, 1, 2 It cannot be the pop sequence of the push sequence. (Note: the two sequences are of equal length)

Idea: Python judges whether the pop-up sequence of the stack is legal

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if not pushV or len(pushV)!=len(popV):
            return 0
        stack = []
        for v in pushV:
            stack.append(v)
            while len(stack) and stack[-1]==popV[0]:
                stack.pop()
                popV.pop(0)
        if len(stack):
            return 0
        return 1

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324822709&siteId=291194637
Recommended