Stacks: Balanced Brackets

  • + 0 comments

    Python O(n)

    def isBalanced(expression):
        stack = []
        for ind in range(len(expression)):
            elem = ''
            if expression[ind] in '([{':
                stack.append(expression[ind])
            elif len(stack) > 0:
                elem = stack.pop()
            else:
                return 'NO'
            
            if (expression[ind] in ')' and elem != '(') \
                or (expression[ind] in '}' and elem != '{') \
                or (expression[ind] in ']' and elem != '['):
                return 'NO'
        return 'YES' if len(stack) == 0 else 'NO'