Skip to content

Commit ef684ed

Browse files
authored
add 772 py3
1 parent f82785c commit ef684ed

File tree

1 file changed

+28
-1
lines changed
  • solution/0700-0799/0772.Basic Calculator III

1 file changed

+28
-1
lines changed

solution/0700-0799/0772.Basic Calculator III/README.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,34 @@ tags:
7373
#### Python3
7474

7575
```python
76-
76+
class Solution:
77+
def calculate(self, s: str) -> int:
78+
def dfs(q):
79+
num, sign = 0, "+"
80+
stk = []
81+
while q:
82+
c = q.popleft()
83+
if c.isdigit():
84+
num = num * 10 + int(c)
85+
if c == "(":
86+
num = dfs(q)
87+
if c in "+-*/)" or not q:
88+
#! careful we catch ')' to eval (...), ow (4-5/2) will only be sum([4,-5]) => -1, /2 is ignored
89+
if sign == "+":
90+
stk.append(num)
91+
elif sign == "-":
92+
stk.append(-num)
93+
elif sign == "*":
94+
stk.append(stk.pop() * num)
95+
elif sign == "/":
96+
stk.append(int(stk.pop() / num))
97+
sign = c
98+
num = 0
99+
if c == ")":
100+
break
101+
return sum(stk)
102+
103+
return dfs(deque(s))
77104
```
78105

79106
#### Java

0 commit comments

Comments
 (0)