-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicCalculator.py
More file actions
28 lines (25 loc) · 818 Bytes
/
Copy pathbasicCalculator.py
File metadata and controls
28 lines (25 loc) · 818 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
class Solution:
# Time complexity - O(n), Space Complexity - O(d), d - max depth of parentheses
def calculate(self, s: str) -> int:
cur = 0
res = 0
sign = 1
stack = []
for ch in s:
if ch == " ": continue
if ch.isdigit():
cur = cur * 10 + int(ch)
else:
res += cur * sign
cur = 0
sign = 1 if ch == "+" else (-1 if ch == "-" else sign)
if ch == "(":
stack.append(res)
stack.append(sign)
cur = 0
sign = 1
res = 0
elif ch == ")":
res *= stack.pop()
res += stack.pop()
return res + cur * sign