一、题目地址
https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
二、具体代码
/**
* @param {string[]} tokens
* @return {number}
*/
// 时间复杂度: O(n),n为tookens的长度
// 空间复杂度: O(n),n为stack的长度
var evalRPN = function(tokens) {
let stack = [];
for(let i=0; i<tokens.length; i++) {
let token = tokens[i];
if(token === '+') {
let num1 = stack.pop();
let num2 = stack.pop();
stack.push(num2 + num1);
continue;
}
if(token === '-') {
let num1 = stack.pop();
let num2 = stack.pop();
stack.push(num2 - num1);
continue;
}
if(token === '*') {
let num1 = stack.pop();
let num2 = stack.pop();
stack.push(num2 * num1);
continue;
}
if(token === '/') {
let num1 = stack.pop();
let num2 = stack.pop();
stack.push(Math.trunc(num2 / num1));
continue;
}
stack.push(parseInt(token));
}
return stack.pop();
};
三、补充部分
关注公众号:【深漂程序员小庄】:
内含丰富的学习资源和面试经验(不限前端、java),还有学习交流群可加,并且还有各大厂大佬可一起交流学习,一起进步~添加小庄微信,回复【加群】,可加入互联网技术交流群: