-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatching_brackets.py
More file actions
29 lines (22 loc) · 817 Bytes
/
matching_brackets.py
File metadata and controls
29 lines (22 loc) · 817 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
def match_pair(s: str) -> bool:
char_map = {
'(': ')',
'{': '}',
'[': ']'
}
char_stack = []
for char in s:
# check if the character is in our hash map / is an 'opener'
if char in char_map:
# add its 'closer' to the top of the stack
char_stack.append(char_map[char])
# if it isn't, check if we have this character at the top of the stack
else:
if char_stack and char_stack[-1] == char:
char_stack.pop()
# if we don't, that means that this character has no opening bracket
else:
return False
return True if not char_stack else False # if the stack is empty, then we matched everything
test_str = '(){}[]()({[{}]})'
print(match_pair(test_str))