The leetcode question is :
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order.
My code:
class Solution:
def isValid(self, s: str) -> bool:
mapper = {')':'(',
']':'[',
'}':'{'}
stack = []
top_element = -1
if not s:
return False
for char in s:
if char in mapper and top_element == -1:
return False
if char in mapper and mapper[char] == top_element:
stack.pop()
else:
stack.append(char)
top_element = stack[-1]
return not stack
The logic works for '()' input but not for '{[]}'. I think the error is in the if-else condition
What am I doing wrong?