-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgrouping_symbols_matching.py
51 lines (42 loc) · 1.4 KB
/
grouping_symbols_matching.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
This implementation demonstrates how
to efficiently determine if the opening
and closing brackets of an arithmetic
expression match up correctly.
Example:
For following expression: (1 + 2)
The output would be: true
However, for the following one: (1 + 2]
The output would be: false
Let n be the number of tokens that make up
the arithmetic expression.
Time complexity: O(n)
Space complexity: O(n)
"""
def validate_expression(expression):
opening_symbols = "([{"
closing_symbols = ")]}"
# A map associating opening with closing
matching_symbols = {")": "(", "]": "[", "}": "{"}
stack = []
for token in expression:
# Add an opening symbol to stack
if token in opening_symbols:
stack.append(token)
elif token in closing_symbols:
# For a closing symbol stack cannot be empty
if is_empty(stack):
return False
if stack[-1] == matching_symbols[token]:
# If closing symbol match opening at top of stack
# pop the top element
stack.pop()
else:
# Closing and opening don't match up
return False
# Stack should be empty after processing all tokens
return is_empty(stack)
def is_empty(stack):
return len(stack) == 0
print(validate_expression("([1 + 2])")) # True
print(validate_expression("([1 + 2)")) # False