I tried another approach by splitting the input into two halves and then comparing both halves
here is my code and it works :)
def balanced_brackets(s):
brackets = {'(':')', '[':']', '{':'}'}
if len(s)%2 != 0:
return False
half_s_len=len(s)//2-1
half_s= s[:half_s_len]
for i in range(len(half_s)):
if not (s[i] in brackets and brackets[s[i]] == s[(-1-i)]):
return False
return True
1 answers ( 0 marked as helpful)
The input is not necessarily symmetrical. It will give a false negative in this case:
balanced_brackets('[][({})]')