题目描述:
代码实现:
- 关键在于理解题意,运用栈存储数字,遍历到运算符,则取栈顶两个元素运算即可。
- 时间复杂度:O(n)
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function(tokens) {
var calculate = (s1, s2, char) => {
switch (char) {
case "+":
return s1 + s2
case "-":
return s1 - s2
case "*":
return s1 * s2
case "/":
return Math.trunc(s1 / s2)
}
}
var stack = []
var res = 0
for (var i = 0; i < tokens.length; i++ ) {
if (tokens[i] === "+" || tokens[i] === "-" || tokens[i] === "*" || tokens[i] === "/") {
var s2 = stack.pop(),
s1 = stack.pop()
res = calculate(Number(s1), Number(s2), tokens[i])
stack.push(res)
} else {
stack.push(tokens[i])
}
}
return stack.pop()
}