File tree Expand file tree Collapse file tree 1 file changed +10
-23
lines changed Expand file tree Collapse file tree 1 file changed +10
-23
lines changed Original file line number Diff line number Diff line change @@ -188,34 +188,21 @@ class Solution(object):
188188 return stack.pop()
189189```
190190
191- 另一种可行,但因为使用eval相对较慢的方法 :
191+ 另一种可行,但因为使用eval()相对较慢的方法 :
192192``` python
193- from operator import add, sub, mul
194-
195- def div (x , y ):
196- # 使用整数除法的向零取整方式
197- return int (x / y) if x * y > 0 else - (abs (x) // abs (y))
198-
199193class Solution (object ):
200- op_map = {' +' : add, ' -' : sub, ' *' : mul, ' /' : div}
201-
202- def evalRPN (self , tokens ):
203- """
204- :type tokens: List[str]
205- :rtype: int
206- """
194+ def evalRPN (self , tokens : List[str ]) -> int :
207195 stack = []
208196 for token in tokens:
209- if token in self .op_map:
210- op1 = stack.pop()
211- op2 = stack.pop()
212- operation = self .op_map[token]
213- stack.append(operation(op2, op1))
197+ # 判断是否为数字,因为isdigit()不识别负数,故需要排除第一位的符号
198+ if token.isdigit() or (len (token)> 1 and token[1 ].isdigit()):
199+ stack.append(token)
214200 else :
215- stack.append(int (token))
216- return stack.pop()
217-
218-
201+ op2 = stack.pop()
202+ op1 = stack.pop()
203+ # 由题意"The division always truncates toward zero",所以使用int()可以天然取整
204+ stack.append(str (int (eval (op1 + token + op2))))
205+ return int (stack.pop())
219206```
220207
221208### Go:
You can’t perform that action at this time.
0 commit comments