-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
224.py
69 lines (60 loc) · 2.02 KB
/
224.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
62
63
64
65
66
67
68
69
__________________________________________________________________________________________________
sample 64 ms submission
#
# @lc app=leetcode id=224 lang=python3
#
# [224] Basic Calculator
def my_calculate(expr: str) -> int:
stack = []
operand = result = 0
sign = 1
for ch in expr:
if ch in "0123456789":
operand = (operand * 10) + int(ch)
elif ch in "+-":
result = result + (sign * operand)
operand = 0
sign = 1 if ch == '+' else -1
elif ch in '()':
if ch == '(':
stack.append(result)
stack.append(sign)
operand = result = 0
sign = 1
elif ch == ')':
result = result + (sign * operand)
result = (result * stack.pop()) + stack.pop()
operand = 0
sign=1
return result + (sign * operand)
class Solution:
def calculate(self, s: str) -> int:
return my_calculate(expr=s)
__________________________________________________________________________________________________
sample 13152 kb submission
class Solution:
def calculate(self, s: str) -> int:
res = 0
sign = 1
num = 0
stack = []
for i in range(len(s)):
if s[i].isdigit():
num = num * 10 + int(s[i])
if s[i] == "+" or s[i] == "-":
res += num * sign
num = 0
sign = 1 if s[i] == "+" else -1
if s[i] == "(":
stack.append(res)
stack.append(sign)
res = 0
sign = 1
if s[i] == ")":
res += num * sign
res *= stack.pop()
res = res + stack.pop()
num = 0
sign = 1
return res + num*sign
__________________________________________________________________________________________________