Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the push-in and pop-up sequence of stack by LeetCode

Shulou Source: shulou.com Published: 2022-06-02 06:35:31 10月30日 Update

This article mainly shows you "how LeetCode realizes the push and pop sequence of the stack". The content is simple and easy to understand, and the organization is clear. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "how LeetCode realizes the push and pop sequence of the stack".

Title Description

Enter two integer sequences. The first sequence indicates the push order of the stack. Please determine whether the second sequence may be the pop order of the stack. Assume that all the numbers pushed into the stack are unequal. For example, sequence 1, 2, 3, 4, 5 is the push sequence of a stack, sequence 4, 5, 3, 2, 1 is a pop sequence corresponding to the push sequence, but 4, 3, 5, 1, 2 cannot be the pop sequence of the push sequence. (Note that the lengths of these two sequences are equal.)

class Solution: def IsPopOrder(self, pushV, popV): if not pushV or not popV or len(pushV) != len(popV): return False stack = [] for pop in popV: #For each element in the pop-up sequence, if it is not at the top of the stack, then push it one by one from the push sequence until the top element is #Elements to be ejected. #If the push sequence is empty and the pop-up sequence is not found at the top of the stack, it means that the pop-up sequence and the push sequence cannot match. if not stack or stack[-1] != pop: while pushV: stack.append(pushV[0]) if pushV.pop(0) == pop: break if stack and stack[-1] == pop: stack.pop(-1) else: return False return True The above is "LeetCode how to achieve stack push, pop sequence" All the contents of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Tags: Sequence elements content articles order two learning help numbers integers easy to understand more organization knowledge editing industry information information channels length channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Technology Shulou Information Linux Docker