Problem :

https://www.hackerrank.com/challenges/balanced-brackets/problem


My Solution :

#!/usr/bin/python3


def isBalanced(s):
    if len(s) % 2 != 0:
        return 'NO'
    pairs = {
        '(': ')',
        '{': '}',
        '[': ']',
    }
    stack = []
    for bracket in s:
        if bracket in pairs:
            stack.append(bracket)
        else:
            if stack and pairs[stack.pop()] == bracket:
                continue
            else:
                return 'NO'
    if stack:
        return 'NO'
    return 'YES'


t = int(input())
for _ in range(t):
    s = input()
    result = isBalanced(s)
    print(result)