SHARE
TWEET

980. Basic Calculator II

goodwish Oct 15th, 2019 (edited) 121 in 126 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Q: 给你一个字符串, 里边包含数字, " +-*/ ", 解析和计算出它的结果.
  2. 思路:
  3. 做两遍扫描, 第一遍算乘除, 第二遍算加减.
  4. i.e. if op_stack[-1] == "*": num_stack[-1] *= num; op_stack.pop(); 乘除,在栈顶就地计算.
  5.  
  6. 数据结构: 两个 stack.
  7. op_stack: 存运算符.
  8. num_stack: 存数字.
  9. .
  10.  
  11. class Solution:
  12.     def calculate(self, s):
  13.         # init
  14.         op_stack, num_stack = ["+"], []
  15.         num_str = ""
  16.         s = s.strip()
  17.         n = len(s)
  18.         for i, c in enumerate(s):
  19.             if c == " ":
  20.                 continue
  21.             if c.isdigit():
  22.                 num_str += c
  23.             if (i == n - 1 or not c.isdigit()) and num_str:
  24.                 num = int(num_str)
  25.                 if op_stack[-1] == "*":
  26.                     num_stack[-1] = num_stack[-1] * num
  27.                     op_stack.pop()
  28.                 elif op_stack[-1] == "/":
  29.                     num_stack[-1] = num_stack[-1] // num
  30.                     op_stack.pop()
  31.                 else:
  32.                     num_stack.append(num)
  33.                 num_str = ""
  34.             if c in ("+-*/"):
  35.                 op_stack.append(c)
  36.         # print(op_stack, num_stack)
  37.         tot = 0
  38.         while num_stack:
  39.             op = op_stack.pop()
  40.             v = num_stack.pop()
  41.             if op == "+":
  42.                 tot += v
  43.             elif op == "-":
  44.                 tot -=v
  45.         return tot
  46.  
  47. s = " 3/2 "
  48. s = " 3 + 2* 2"
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top