Balanced Brackets

  • + 0 comments

    This is my python solution. It's consise and self explanatory if you understand the application of a stack.

    def isBalanced(s):
        stack = []
        open_to_close = {"{": "}", "[": "]", "(": ")"}
        for bracket in s:
            # Open bracket case
            closing_bracket = open_to_close.get(bracket)
            if closing_bracket:
                stack.append(closing_bracket)
            # Close bracket case
            elif not stack or bracket != stack.pop():
                return "NO"
        
        # If we have looped through the entire string and the stack is empty, all opening brackets were closed
        return "NO" if stack else "YES"