Skip to content

Instantly share code, notes, and snippets.

@liyunrui
Created September 10, 2021 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liyunrui/d027e8ba61df137590217895c1325fa1 to your computer and use it in GitHub Desktop.
Save liyunrui/d027e8ba61df137590217895c1325fa1 to your computer and use it in GitHub Desktop.
class Solution:
"""
"2*(5+5*2)/3+(6/2+8)"
i
"""
def calculate(self, s: str) -> int:
def cal_update(op, num, stack):
if op == "+":
stack.append(num)
elif op == "-":
stack.append(-num)
elif op == "*":
stack.append(stack.pop()*num)
elif op == "/":
stack.append(int(stack.pop()/num))
s = s+"+"
n = len(s)
i = 0
num = 0
stack = []
op = "+"
while i < n:
ch = s[i]
if ch.isdigit():
num*=10
num+=ord(ch)-ord("0")
elif ch in set("+-*/"):
cal_update(op, num, stack)
num = 0
op = ch
elif ch == "(":
stack.append(op)
num=0
op="+"
elif ch == ")":
cal_update(op, num, stack)
res_in_paren = 0
while stack[-1] not in set("+-*/"):
res_in_paren+=stack.pop()
op = stack.pop() # 左括號旁邊的符號
cal_update(op, res_in_paren, stack)
#num = 0 # 右括號後不會直接遇到數子肯定是+-*/所以不需要把num歸0也不影響
#不要忘記更新當前op, 當單前op是右括號, 下次再做cal_update就不會放入stack任何res
op = ch
i+=1
return sum(stack)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment