Balanced Brackets

  • + 0 comments
    def isBalanced(s):
        stack = []
        open_brackets = ['(', '[', '{']
        close_brackets = [')', ']', '}']
        
        result = 'YES'
        
        if len(s) > 1:
            for char in s:
                if char in open_brackets:
                    stack.append(char)
                elif char in close_brackets:
                    if (
                        (char == ')' and stack and stack[-1] == '(') or
                        (char == ']' and stack and stack[-1] == '[') or
                        (char == '}' and stack and stack[-1] == '{')
                    ):
                        stack.pop()
                    else:
                        result = 'NO'
                        break
    
        else:
            result = 'NO'
    
        if stack or result == 'NO':
            return 'NO'
    
        return 'YES'