|
1 | 1 | # Time: O(n)
|
2 | 2 | # Space: O(n)
|
3 | 3 |
|
| 4 | +import operator |
| 5 | + |
4 | 6 |
|
5 | 7 | class Solution(object):
|
| 8 | + def calculate(self, s): |
| 9 | + """ |
| 10 | + :type s: str |
| 11 | + :rtype: int |
| 12 | + """ |
| 13 | + def compute(operands, operators): |
| 14 | + right, left = operands.pop(), operands.pop() |
| 15 | + operands.append(ops[operators.pop()](left, right)) |
| 16 | + |
| 17 | + ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div} |
| 18 | + precedence = {'+':0, '-':0, '*':1, '/':1} |
| 19 | + operands, operators, operand = [], [], 0 |
| 20 | + for i in xrange(len(s)): |
| 21 | + if s[i].isdigit(): |
| 22 | + operand = operand*10 + int(s[i]) |
| 23 | + if i == len(s)-1 or not s[i+1].isdigit(): |
| 24 | + operands.append(operand) |
| 25 | + operand = 0 |
| 26 | + elif s[i] == '(': |
| 27 | + operators.append(s[i]) |
| 28 | + elif s[i] == ')': |
| 29 | + while operators[-1] != '(': |
| 30 | + compute(operands, operators) |
| 31 | + operators.pop() |
| 32 | + elif s[i] in precedence: |
| 33 | + while operators and operators[-1] in precedence and \ |
| 34 | + precedence[operators[-1]] >= precedence[s[i]]: |
| 35 | + compute(operands, operators) |
| 36 | + operators.append(s[i]) |
| 37 | + while operators: |
| 38 | + compute(operands, operators) |
| 39 | + return operands[-1] |
| 40 | + |
| 41 | + |
| 42 | +# Time: O(n) |
| 43 | +# Space: O(n) |
| 44 | +class Solution2(object): |
6 | 45 | # @param {string} s
|
7 | 46 | # @return {integer}
|
8 | 47 | def calculate(self, s):
|
|
0 commit comments