Balanced Brackets

  • + 0 comments

    Quick solution in Python 3:

    def isBalanced(s):
        history = []
        
        for bracket in s:
            if bracket == '(':
                history.append(')')
            elif bracket == '{':
                history.append('}')
            elif bracket == '[':
                history.append(']')
            else:
                if not history or bracket != history.pop():
                    return 'NO'
                    
        return 'YES' if not history else 'NO'