【leetcode】227. Basic Calculator II
题目如下:
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negativeintegers,
+
,-
,*
,/
operators and empty spaces. The integer division should truncate toward zero.
Example 1:
Input: "3+2*2" Output: 7Example 2:
Input: " 3/2 " Output: 1Example 3:
Input: " 3+5 / 2 " Output: 5Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
解题思路:我的方法分成两部分,第一部分是先计算乘除,完成后再计算表达式中剩余的加减。从头开始遍历Input,并用list保存把每个操作数和操作符保存起来,如果遇到'*'或者'/'操作符,把list中最后一个元素和操作符后面的第一个元素进行计算,求得值后更新到list中最后一个元素,这样list中就剩下加减操作,再计算一次即可。例如"1+2*3*4",在计算过程中list中保存的内容如下所示,
[]
[1]
[1, '+']
[1, '+',2]
[1, '+', 2, '*']
[1, '+', 6]
[1, '+', 6, '*']
[1, '+', 12]
[1, '+', 12, '*']
[1, '+', 24]
最后在计算加减的时候,我用了list的pop方法(如下面代码中注释掉的部分),结果超时了,但是通过下标遍历就可以通过。看来在python里面,pop方法的效率非常低。
代码如下:
class Solution(object): """ :type s: str :rtype: int """ def calculate(self, s): l = [] s += '#' operator = ['+', '-', '*', '/', '#'] last = '' for i in s: if i in operator: if len(l) > 0 and l[-1] in ['*','/']: op = l.pop(-1) if op == '*': v = l[-1] * int(last) else: v = l[-1] / int(last) l[-1] = v else: l.append(int(last)) last = '' if i != '#': l.append(i) elif i != ' ': last += i ''' # time exceed limit val = l.pop(0) while len(l) >= 2: op = l.pop(0) next_val = l.pop(0) if op == '+': val += next_val else: val -= next_val return val ''' val = l[0] for i in range(1,len(l)-1,2): op = l[i] next_val = l[i+1] if op == '+': val += next_val else: val -= next_val return val