-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalance_brackets.py
More file actions
31 lines (24 loc) · 847 Bytes
/
balance_brackets.py
File metadata and controls
31 lines (24 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
###check if a string of brackets in balanced
OPENING_BRACKETS = {"{", "[", "("}
BRACKETS_MAP = {"]": "[", "}": "{", ")": "("}
def isValid(s):
stack = []
for bracket in s:
if bracket in OPENING_BRACKETS:
stack.append(bracket)
elif not stack:
return False # Can't pop from an empty stack
elif stack.pop() != BRACKETS_MAP[bracket]:
return False # Closing the wrong kind of bracket
return not stack
print(isValid('{[][[]][]()[]'))
#######################Shorter version
BRACKETS_MAP = {"[": "]", "{": "}", "(": ")"}
def isValid(s):
stack = []
for bracket in s:
if bracket in BRACKETS_MAP:
stack.append(BRACKETS_MAP[bracket])
elif not stack or bracket != stack.pop():
return False
return not stack