0

I am doing the Leetcode valid parenthesis question and want to implement the ans using deque stack. there are three types of parenthesis {[()]} and i need to check the top of the stack before i pop it.

i couldnt find any method for collections.deque similar to list stack peek()

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

i know this code doesn't work already and is incomplte, for example:

if stack.maxlen() is not None:

this cant work, i am still working on the syntax and logic.

i need a way to see the top of the stack in below part of code in the "if condition"

if(s[i]=="}" and "{"==stack[-1]):
                stack.pop()
  • `stack[-1]` is the equivalent of `stack.peek()` if you will. Most stack implementations raise an Error if `peek` is called when empty. – user2390182 Apr 21 '23 at 09:53
  • @user2390182 so i checked separately for this. and yes for collections.deque stack[-1] works. for me it must have given error due to stack being empty. there's no peek function for collections.deque though. thanks!!! –  Prathamesh Padhye Apr 21 '23 at 13:36

1 Answers1

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])

so this gives answer 4.

my code was giving me error because stack was empty, i will work my way for that. and there is no peek attribute for collections.deque.

AttributeError: 'collections.deque' object has no attribute 'peek'