Leet Code

#4 20. Valid Parentheses

brian | Published: Aug. 16, 2024, 8:10 p.m. | Updated: July 9, 2025, 8:02 p.m.

Profile Picture
'''
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']',
determine if the input string is valid.

Input: s = "()[]{}"
Output: true
'''


class Solution:
    def solve(self, s:str):
        #create an empty stack
        stack = []
        #create a hash with all the keys as the closing tags and the vals as the opening version of them
        closeToOpen = {
            '}':  '{',
            ']':  '[',
            ')':  '(',
        }

        for char in s:
            print(stack)
            #if the char is in the closeToOpen, that means the current char has to be a closing tag
            if char in closeToOpen:
                #and if the stack is NOT empty and the last value is equal (=) to the opening tag variant
                if stack and stack[-1] == closeToOpen[char]:
                    #then we pop the value
                    stack.pop()
                else:
                    return False
            else:
                stack.append(char)
               
         #if the stack is empty then return True else return False
        return True if not stack else False
                

        

    


s = '([])'

perk = Solution()
print(perk.solve(s))




-----------output----------
[]
['(']
['(', '[']
['(']
True