描述:计算逆波兰表达法的结果
Sample:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
使用stack实现:
1 def is_op(c): 2 return c in [‘+‘, ‘-‘, ‘*‘, ‘/‘] 3 4 def divide(x, y): 5 if (x * y) < 0: 6 return -1 * ((-x)/y) 7 return x/y 8 9 class Solution: 10 # @param tokens, a list of string 11 # @return an integer 12 def evalRPN(self, tokens): 13 opDict = {‘+‘: lambda x,y: x+y, 14 ‘-‘: lambda x,y: x-y, 15 ‘*‘: lambda x,y: x*y, 16 ‘/‘: divide} 17 record = [] 18 19 for item in tokens: 20 if is_op(item): 21 second = record.pop() 22 first = record.pop() 23 record.append(opDict[item](first, second)) 24 else: 25 record.append(int(item)) 26 return record[0]
使用树实现:
Todo
备注:python的除法跟c++不太一样 3/-5 = -1
结论:
根据问题的具体特性,选择合适的数据结构解决问题会差别很大
#Leet Code# Evaluate Reverse Polish Notation,布布扣,bubuko.com
时间: 2024-10-22 12:35:35