Skip to content

Instantly share code, notes, and snippets.

@hmenn
Created July 12, 2017 20:07
Show Gist options
  • Save hmenn/3767518b4f304ea407f05e891d6fd624 to your computer and use it in GitHub Desktop.
Save hmenn/3767518b4f304ea407f05e891d6fd624 to your computer and use it in GitHub Desktop.
Interview_cake_147_bracket_validator
open_brackets =['{','[','(']
close_brackets = ['}',']',')']
def getIndex(l,ch):
index=None
try:
index=l.index(ch)
except:
index=None
return index
"""
j=0
for i in l:
if i == ch:
return j
else:
j=j+1
"""
def isBracketsValid(str):
brackets = []
for ch in str:
#print(ch)
index_open = getIndex(open_brackets,ch)
if index_open != None:
brackets.append(ch)
else:
index_close = getIndex(close_brackets,ch)
if index_close != None:
match_index = getIndex(open_brackets,brackets.pop())
if match_index==index_close:
continue
else:
return False
return True
def main():
testStr1 = "{([])}"
testStr2 = "{ [ ( ] ) }"
print(testStr1," : ", isBracketsValid(testStr1))
print(testStr2," : ", isBracketsValid(testStr2))
if __name__=="__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment