Skip to content

Commit bcf6522

Browse files
authored
Add Basic Calculator III solution
1 parent afe46d7 commit bcf6522

File tree

1 file changed

+26
-0
lines changed
  • solution/0700-0799/0772.Basic Calculator III

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def calculate(self, s: str) -> int:
3+
def dfs(q):
4+
num, sign, stk = 0, "+", []
5+
while q:
6+
c = q.popleft()
7+
if c.isdigit():
8+
num = num * 10 + int(c)
9+
if c == "(":
10+
num = dfs(q)
11+
if c in "+-*/)" or not q:
12+
match sign:
13+
case "+":
14+
stk.append(num)
15+
case "-":
16+
stk.append(-num)
17+
case "*":
18+
stk.append(stk.pop() * num)
19+
case "/":
20+
stk.append(int(stk.pop() / num))
21+
num, sign = 0, c
22+
if c == ")":
23+
break
24+
return sum(stk)
25+
26+
return dfs(deque(s))

0 commit comments

Comments
 (0)