Question
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Example 2:
Example 3:
Note:
Solution
Naive (Timeout)
- class Solution:
- def calculate(self, s: str) -> int:
- stack = []
- # 0) Building stack
- num = ''
- for c in s.strip():
- if c in ['+', '-', '*', '/']:
- stack.append(int(num))
- stack.append(c)
- num = ''
- continue
- elif c == ' ':
- continue
- num += c
- if num:
- stack.append(int(num))
- def index_of(i):
- for j in range(i, len(stack)):
- if stack[j] in ['*', '/']:
- return j
- return -1
- # 1) Start calculation
- # 1.1) Handle high priority op (/,*)
- i = index_of(0)
- while i > 0:
- hop = stack[i]
- num1 = stack[i-1]
- num2 = stack[i+1]
- if hop == '/':
- stack[i-1:i+2] = [num1//num2]
- else:
- stack[i-1:i+2] = [num1*num2]
- i = index_of(i)
- # 1.2) Handle low priority op (+/-)
- while len(stack) > 1:
- num1 = stack.pop(0)
- op = stack.pop(0)
- num2 = stack.pop(0)
- if op == '+':
- stack.insert(0, num1 + num2)
- else:
- stack.insert(0, num1 - num2)
- # 2) Return the final result
- return stack[0]
- class Solution:
- def calculate(self, s: str) -> int:
- num, preop, stack = '', '+', []
- for c in s+'+':
- if c.isdigit():
- num += c
- elif c == ' ':
- continue
- elif num != '':
- if preop == '+':
- stack.append(int(num))
- elif preop == '-':
- stack.append(int(num) * -1)
- elif preop == '*':
- stack.append(int(num) * stack.pop())
- else:
- stack.append(math.trunc(stack.pop()/int(num)))
- num = ''
- preop = c
- return sum(stack)
Supplement
* Leetcode: 227 Basic Calculator II 讲解 (Cspiration 官方频道)
沒有留言:
張貼留言