• + 1 comment

    My solution:

    def is_balanced(string):
        b_stc=[]
        closing=[')',']','}']
        opening=['(','[','{']
        
        for ch in string:
            if ch in opening:
                b_stc.append(ch)
            else:
                if not b_stc:
                    return "NO"
                last=b_stc.pop()
                if opening.index(last) != closing.index(ch):
                    return "NO"
        return "NO" if b_stc else "YES" 
    
    t = int(input().strip())
    for x in range(t):
        s = input().strip()
        print(is_balanced(s))