【LeetCode】逆波兰表达式求值

还记得这个题目曾经是大学数据结构课的第一个实验,只是当时的场景更复杂一些,比如没有做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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值