Skip to content

Commit e529e28

Browse files
committed
Time: 47 ms (88.57%), Space: 22.1 MB (15.75%) - LeetHub
1 parent 49b75f4 commit e529e28

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
import math
4+
5+
6+
class Solution:
7+
def calculate(self, s: str) -> int:
8+
num = 0
9+
prevOperation = '+'
10+
s += '+'
11+
stack = []
12+
for c in s:
13+
if c.isdigit():
14+
num = num*10 + int(c)
15+
elif c == ' ':
16+
pass
17+
else:
18+
if prevOperation == '+':
19+
stack.append(num)
20+
elif prevOperation == '-':
21+
stack.append(-num)
22+
elif prevOperation == '*':
23+
operant = stack.pop()
24+
stack.append((operant*num))
25+
elif prevOperation == '/':
26+
operant = stack.pop()
27+
stack.append(math.trunc(operant/num))
28+
num = 0
29+
prevOperation = c
30+
return sum(stack)
31+
32+
33+
s = "3+2*2"
34+
print(Solution().calculate(s))
35+
s = " 3/2 "
36+
print(Solution().calculate(s))
37+
s = " 3+5 / 2 "
38+
print(Solution().calculate(s))

0 commit comments

Comments
 (0)