Created
March 23, 2022 19:16
-
-
Save joan0fsnark/dc2743cbc977a2d94237ba7d0efc355a to your computer and use it in GitHub Desktop.
Keep Track of Brackets (interview q)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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