Skip to content

Instantly share code, notes, and snippets.

@joan0fsnark
Created March 23, 2022 19:16
Show Gist options
  • Save joan0fsnark/dc2743cbc977a2d94237ba7d0efc355a to your computer and use it in GitHub Desktop.
Save joan0fsnark/dc2743cbc977a2d94237ba7d0efc355a to your computer and use it in GitHub Desktop.
Keep Track of Brackets (interview q)
# Will use this to keep track of type opened
# (1/2/3 == curved/curly/square)
opentype = []
typedict = {
'(': (True, 1),
')': (False, 1),
'[': (True, 2),
']': (False, 2),
'{': (True, 3),
'}': (False, 3)
}
for char in s:
do_open, type = typedict[char]
// True , 1 //
if do_open:
opentype.append(type)
else:
if not opentype: # Nothing to close - fail
return False
elif type == opentype[-1]: # Check against last opened type
opentype.pop() # Successful close
else:
return False # Any bad close quits immediately
# Check that we did close everything we opened
if not opentype:
return True
else:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment