Balanced Brackets

  • + 1 comment

    Python solution:

    My solution avoids to read types of brackets:

    -opening brackets have even values

    -closing brackets have odd values next to the corresponding opening bracket We then just need to check that an odd value doesn't fill an empty stack or that there is no even value in the stack different from the expected one.

    def isBalanced(s):
        if len(s) % 2 != 0:
            return "NO"
        mydict = {}
        mydict["{"] = 0
        mydict["}"] = 1
        mydict["["] = 2
        mydict["]"] = 3
        mydict["("] = 4
        mydict[")"] = 5
        line = []
        for ind in range(len(s)):
            if mydict[s[ind]] % 2 == 0:
                line.append(mydict[s[ind]])
                continue
            if not line:
                return "NO"
            for ind2, elem in enumerate(line[::-1]):
                if elem == mydict[s[ind]] - 1:
                    line.pop(- 1 - ind2)
                    break
                else:
                    if elem % 2 == 0:
                        return "NO"
        if line:
            return "NO"
        return "YES"