Balanced Brackets

  • + 0 comments

    Python

    def getKey(c):
        if(c == '{'): return 1
        if(c == '}'): return 2
        if(c == '('): return 3
        if(c == ')'): return 4
        if(c == '['): return 5
        if(c == ']'): return 6
    
        
    def isBalanced(s):
        # Write your code here
        arrCharacter  = list(s)
        stack = []
        for x in arrCharacter:
            if(len(stack)==0 or getKey(x) != 1+getKey(stack[-1])):
                stack.append(x)
            else:
                stack.pop()
        print(stack)
        return "YES" if len(stack)==0 else "NO"