如何使用 collections.deque 实现栈顶

问题描述 投票:0回答:1

我正在做 Leetcode 有效括号问题,并想使用双端队列堆栈实现 ans。 有三种类型的括号 {[()]} 我需要在弹出它之前检查堆栈的顶部。

我找不到任何类似于 list stack peek() 的 collections.deque 方法

from collections import deque

class Solution:
    def isValid(self, s: str) -> bool:
        stack=deque()
        for i in range(len(s)):
            if(s[i]=="{"):
                stack.append("{")
            elif(s[i]=="("):
                stack.append("(")
            elif(s[i]=="["):
                stack.append("[")
            if stack.maxlen() is not None:
                if(s[i]=="}" and "{"==stack[-1]):
                    stack.pop()
                elif(s[i]==")" and "("==stack[-1]):
                    stack.pop()
                elif(s[i]=="]" and "["==stack[-1]):
                    stack.pop()
        if(bool(stack)):
            return False
        else:
            return True

我知道这段代码已经无法使用并且不完整,例如:

if stack.maxlen() is not None:

这行不通,我仍在研究语法和逻辑。

我需要一种方法来查看“if 条件”中代码下方部分的堆栈顶部

if(s[i]=="}" and "{"==stack[-1]):
                stack.pop()
python-3.x stack deque python-collections
1个回答
0
投票
from collections import deque
stack=deque()
stack.append(1)
stack.append(2)
stack.append(3)
stack.append(4)
# print(stack.peek())
print(stack[-1])

所以这给出了答案 4.

我的代码给我错误,因为堆栈是空的,我会为此努力。 并且 collections.deque 没有 peek 属性。

AttributeError: 'collections.deque' object has no attribute 'peek'
© www.soinside.com 2019 - 2024. All rights reserved.