-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path227.Basic-Calculator-II.py
61 lines (47 loc) · 1.34 KB
/
227.Basic-Calculator-II.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
52
53
54
55
56
57
58
59
60
61
# https://leetcode.com/problems/basic-calculator-ii/description/
#
# algorithms
# Medium (31.8%)
# Total Accepted: 86.8K
# Total Submissions: 272.9K
from collections import deque
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = deque()
s = s.strip()
length = len(s)
idx = 0
while idx < length:
if s[idx] == ' ':
idx += 1
continue
if s[idx].isdigit():
j = idx + 1
while j < length and s[j].isdigit():
j += 1
n = int(s[idx:j])
if stack and (stack[-1] == '*' or stack[-1] == '/'):
op = stack.pop()
pre_num = stack.pop()
if op == '*':
n = n * pre_num
else:
n = pre_num / n
stack.append(n)
idx = j
else:
stack.append(s[idx])
idx += 1
pre_num = stack.popleft()
while stack:
op = stack.popleft()
next_num = stack.popleft()
if op == '+':
pre_num += next_num
else:
pre_num -= next_num
return pre_num