1123. Lowest Common Ancestor of Deepest Leaves
- Lowest Common Ancestor of Deepest Leaves python solution
题目描述
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

解析
进行模拟循环的操作,如果当前进栈元素(pushed)不等于出栈元素(popped),就把进栈元素压入栈中。
如果栈顶元素等于出栈元素(popped),那么就出栈。
最后检测队列是否为空
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
index, stack = 0, []
for p in pushed:
stack.append(p)
while stack and stack[-1] == popped[index]:
stack.pop()
index += 1
return not stack
Reference
https://leetcode.com/problems/validate-stack-sequences/discuss/197667/JavaPython-3-straight-forward-stack-solution.
本文介绍了一种验证栈操作序列正确性的算法。通过模拟栈的push和pop操作,检查给定的pushed和popped序列是否能形成有效的栈操作序列。文章详细解释了算法流程,并提供了Python代码实现。
180

被折叠的 条评论
为什么被折叠?



