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.