Skip to content

Commit 67e4b6c

Browse files
committed
feat(leetcode): add No.227
1 parent 2004032 commit 67e4b6c

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

227.Basic-Calculator-II.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# https://leetcode.com/problems/basic-calculator-ii/description/
2+
#
3+
# algorithms
4+
# Medium (31.8%)
5+
# Total Accepted: 86.8K
6+
# Total Submissions: 272.9K
7+
8+
9+
from collections import deque
10+
11+
12+
class Solution(object):
13+
def calculate(self, s):
14+
"""
15+
:type s: str
16+
:rtype: int
17+
"""
18+
s = s.replace(' ', '')
19+
stack = deque()
20+
i = 0
21+
length = len(s)
22+
23+
while i < length:
24+
if ord(s[i]) >= 48 and ord(s[i]) <= 57:
25+
begin_idx = i
26+
i += 1
27+
while i < length and ord(s[i]) >= 48 and ord(s[i]) <= 57:
28+
i += 1
29+
num = int(s[begin_idx:i])
30+
if len(stack) == 0 or stack[0] == '+' or stack[0] == '-':
31+
stack.appendleft(num)
32+
else:
33+
if stack[0] == '*':
34+
op = stack.popleft()
35+
another_num = stack.popleft()
36+
stack.appendleft(num * another_num)
37+
if stack[0] == '/':
38+
op = stack.popleft()
39+
another_num = stack.popleft()
40+
stack.appendleft(another_num / num)
41+
else:
42+
stack.appendleft(s[i])
43+
i += 1
44+
45+
while len(stack) != 1:
46+
num1 = stack.pop()
47+
op = stack.pop()
48+
num2 = stack.pop()
49+
res = num1 + num2 if op == '+' else num1 - num2
50+
stack.append(res)
51+
52+
return stack[0]

0 commit comments

Comments
 (0)