还记得这个题目曾经是大学数据结构课的第一个实验,只是当时的场景更复杂一些,比如没有做token的切分,需要手动判断数字的边界。
思路
利用栈结构记录中间结果。
解题过程
扫描一遍token流,遇到数字则入栈,遇到运算符则弹出两个数字做运算再入栈,最终结果在栈顶。
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(n)
代码
const operators = ['+', '-', '*', '/'];
function evalRPN(tokens: string[]): number {
const stack: string[] = [];
let index = 0;
while (index < tokens.length) {
const cur = tokens[index];
if (operators.includes(cur)) {
console.log('操作符运算', cur);
// 遇到操作符,弹出两个操作数做运算
const operand2 = Number(stack.pop());
const operand1 = Number(stack.pop());
let result = 0;
switch(cur) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
// 注意向零截断,也可以用 v < 0 ? Math.ceil(v) : Math.floor(v)
result = Math.trunc(operand1 / operand2);
break;
}
console.log(result);
stack.push(String(result));
} else {
console.log('数字入栈', cur);
stack.push(cur);
}
index++;
}
const result = Number(stack.pop());
console.log(result);
return result;
};
449

被折叠的 条评论
为什么被折叠?



