给定一个逆波兰表达式,求表达式的值。
数据范围:表达式长度满足 ,表达式中仅包含数字和 + ,- , * , / ,其中数字的大小满足 。
class Solution: def evalRPN(self , tokens: List[str]) -> int: #辅助栈 st = [] ma = ['+', '-', '*', '/'] # 遍历tokens for i, char in enumerate(tokens): if char not in ma: st.append(int(char)) elif (char in ma) and (len(st) >=2): operator = char result = eval("st[-2] {0} st[-1]".format(operator)) st.pop() st.pop() st.append(result) print(st) return int(st[-1])
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param tokens string字符串一维数组 # @return int整型 # class Solution: def evalRPN(self , tokens: List[str]) -> int: # write code here """ 逆波兰表达式 1. 维护一个栈,栈中只保存数值 -> stack = [] 2. 如果遇到数,存到栈中 3. 如果遇到运算符,从stack中取出两个元素进行相应的计算并存储回栈中 """ stack = [] for elem in tokens: # 如果是运算符 if elem in "+-*/": # 从栈中取出两个元素 first = stack.pop() second = stack.pop() # 根据运算符进行对应计算 if elem == "+": stack.append(second + first) elif elem == "-": stack.append(second - first) elif elem == "*": stack.append(second * first) else: stack.append(int(second / first)) # 如果数 else: stack.append(int(elem)) # 最后取出栈的元素 return stack.pop()