-
Notifications
You must be signed in to change notification settings - Fork 0
/
2020-02-20.py
32 lines (25 loc) · 995 Bytes
/
2020-02-20.py
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
32
"""
Given a string of round, curly, and square open and closing brackets, return whether the
brackets are balanced (well-formed).
For example, given the string `"([])[]({})"`, you should return true.
Given the string `"([)]"` or `"((()"`, you should return false.
"""
def balanced(brackets: str) -> bool:
stack = list()
for idx in range(len(brackets)):
for st, en in [("(", ")"), ("{", "}"), ("[", "]")]:
if brackets[idx] == st:
stack.append(brackets[idx])
elif brackets[idx] == en:
if stack.pop() != st:
return False
return len(stack) == 0
if __name__ == "__main__":
assert balanced("([])[]({})") is True
assert balanced("([)]") is False
assert balanced("((()") is False
assert balanced("(((]]]") is False
assert balanced("((({)))") is False
assert balanced("((({])))") is False
assert balanced("((({})))") is True
assert balanced("[({([])[]({})})]") is True