Balanced Brackets Problem HackerRank

Balanced Brackets Problem HackerRank

Nice problem for that is used on all of our IDEs

simply checking if our brackets fit together.

Problems description here

Solution Brief:

Simply running through each char in the string, checking if its a bracket or not. On our case, it always brackets.
Now if it’s an opening bracket push it into our stack.
If it’s a closing bracket, make sure stack is not empty, cause if so the string is not balanced.
Pop the last bracket from the stack and make sure they are balanced together.

Pseudo Code:
stack  
for c in str  
   if opener, push to stack, next loop

   if closer
      if stack is empty, NOT balanced

      pop last item from stack
      compare the 2,
      if not brothers, NOT balanced

if stack is empty  
   its balanced
else  
   its not
Solution Code:

Github Src

def isCloser(char):  
    closers = ['}', ']', ')']
    return char in closers

def isOpener(char):  
    openers = ['{', '[', '(']
    return char in openers

def isBrothers(opener, closer):  
    return (opener=='{' and closer=='}') or (opener=='[' and closer==']') or (opener=='(' and closer==')')

def is_matched(str):  
    stack = []
    for char in str:
        if isOpener(char):
            stack.append(char)
            continue
        if isCloser(char):
            if (len(stack)==0):
                return False
            prev = stack.pop()
            if not isBrothers(prev, char):
                return False
    return len(stack) == 0

res = is_matched('{[()](})')  
print res  

Leave a Reply

Your email address will not be published. Required fields are marked *