class Solution {
public:
int evalRPN(vector<string>& tokens) {
}
};
150. 逆波兰表达式求值
根据 逆波兰表示法,求表达式的值。
有效的算符包括 +
、-
、*
、/
。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
注意 两个整数之间的除法只保留整数部分。
可以保证给定的逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入:tokens = ["2","1","+","3","*"] 输出:9 解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
示例 2:
输入:tokens = ["4","13","5","/","+"] 输出:6 解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
示例 3:
输入:tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] 输出:22 解释:该算式转化为常见的中缀算术表达式为: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22
提示:
1 <= tokens.length <= 104
tokens[i]
是一个算符("+"
、"-"
、"*"
或 "/"
),或是在范围 [-200, 200]
内的一个整数
逆波兰表达式:
逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。
( 1 + 2 ) * ( 3 + 4 )
。( ( 1 2 + ) ( 3 4 + ) * )
。逆波兰表达式主要有以下两个优点:
1 2 + 3 4 + *
也可以依据次序计算出正确结果。原站题解
java 解法, 执行用时: 7 ms, 内存消耗: 41.9 MB, 提交时间: 2023-09-14 15:42:16
class Solution { public int evalRPN(String[] tokens) { Deque<Integer> stack = new LinkedList<Integer>(); int n = tokens.length; for (int i = 0; i < n; i++) { String token = tokens[i]; if (isNumber(token)) { stack.push(Integer.parseInt(token)); } else { int num2 = stack.pop(); int num1 = stack.pop(); switch (token) { case "+": stack.push(num1 + num2); break; case "-": stack.push(num1 - num2); break; case "*": stack.push(num1 * num2); break; case "/": stack.push(num1 / num2); break; default: } } } return stack.pop(); } public boolean isNumber(String token) { return !("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token)); } }
golang 解法, 执行用时: 4 ms, 内存消耗: 4.5 MB, 提交时间: 2023-09-14 15:42:03
func evalRPN(tokens []string) int { stack := []int{} for _, token := range tokens { val, err := strconv.Atoi(token) if err == nil { stack = append(stack, val) } else { num1, num2 := stack[len(stack)-2], stack[len(stack)-1] stack = stack[:len(stack)-2] switch token { case "+": stack = append(stack, num1+num2) case "-": stack = append(stack, num1-num2) case "*": stack = append(stack, num1*num2) default: stack = append(stack, num1/num2) } } } return stack[0] }
javascript 解法, 执行用时: 80 ms, 内存消耗: 43.7 MB, 提交时间: 2023-09-14 15:41:42
/** * @param {string[]} tokens * @return {number} */ var evalRPN = function(tokens) { const stack = []; const n = tokens.length; for (let i = 0; i < n; i++) { const token = tokens[i]; if (isNumber(token)) { stack.push(parseInt(token)); } else { const num2 = stack.pop(); const num1 = stack.pop(); if (token === '+') { stack.push(num1 + num2); } else if (token === '-') { stack.push(num1 - num2); } else if (token === '*') { stack.push(num1 * num2); } else if (token === '/') { stack.push(num1 / num2 > 0 ? Math.floor(num1 / num2) : Math.ceil(num1 / num2)); } } } return stack.pop(); }; const isNumber = (token) => { return !('+' === token || '-' === token || '*' === token || '/' === token ); }
python3 解法, 执行用时: 60 ms, 内存消耗: 17.5 MB, 提交时间: 2023-09-14 15:41:03
class Solution: def evalRPN(self, tokens: List[str]) -> int: op_to_binary_fn = { "+": add, "-": sub, "*": mul, "/": lambda x, y: int(x / y), # 需要注意 python 中负数除法的表现与题目不一致 } stack = list() for token in tokens: try: num = int(token) except ValueError: num2 = stack.pop() num1 = stack.pop() num = op_to_binary_fn[token](num1, num2) finally: stack.append(num) return stack[0]
python3 解法, 执行用时: 120 ms, 内存消耗: 17.6 MB, 提交时间: 2023-09-14 15:39:58
class Solution: def evalRPN(self, tokens: List[str]) -> int: data = [] sig = ['+', '-', '*', '/'] for token in tokens: if token in sig: right = data.pop() left = data.pop() data.append(eval(f'int({left} {token} {right})')) else: data.append(token) return int(data[0])
php 解法, 执行用时: 44 ms, 内存消耗: 17.3 MB, 提交时间: 2021-05-28 17:09:37
class Solution { /** * @param String[] $tokens * @return Integer */ function evalRPN($tokens) { $data = []; $sig = ['+', '-', '*', '/']; foreach ( $tokens as $token ) { if ( in_array($token, $sig) ) { $right = array_pop($data); $left = array_pop($data); $data[] = eval("return intval({$left}{$token}({$right}));"); } else { $data[] = $token; } } return intval($data[0]); } }