Balanced Brackets Problem HackerRank

Tue Feb 27 2018

Nice problem for that is used on all of our IDEs

simply checking if our brackets fit together.

Problems description here

Solution Brief: {#solutionbrief}

Simply running through each char in the string, checking if its a bracket or not. On our case, it always brackets.

Now if its an opening bracket push it into our stack.

If its 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: {#pseudocode}
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
   its not
Solution Code: {#solutioncode}

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):
        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