【leetcode】150.逆波兰表达式求值js

碎碎念

字节你让我哭!

题目

代码

就是通过栈,遇到数字进栈,遇到运算符两个数出栈做运算,结果又入栈,直到遍历完则栈里的元素就是最终的运算结果。

需要注意的点是tokens里全是字符,数字要强制类型转换,运算符也要做处理。

javascript 复制代码
/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function(tokens) {
    const len = tokens.length
    if (len === 1) return Number(tokens[0])
    const st = []
    const s = new Set(['+', '-', '*', '/'])
    const operations = {
        '+': (x, y) => x + y,
        '-': (x, y) => x - y,
        '*': (x, y) => x * y,
        '/': (x, y) => Math.trunc(x / y)
    }
    for (let i = 0; i < len; i++) {
        if (!s.has(tokens[0])) {
            st.push(tokens[0])
        } else {
            const num1 = Number(st.pop())
            const num2 = Number(st.pop())
            const op = tokens[0]
            st.push(operations[op](num2, num1))
        }
        tokens.shift()
    }
    return st[0]
};

更快的做法

上面这个用了10ms才过。看题解用switch-case更快些,于是试试。

javascript 复制代码
/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function(tokens) {
    const st = []
    tokens.forEach(token => {
        let num = 0
        switch(token) {
            case '+':
                num = st.pop()
                st.push(st.pop() + num)
                break
            case '-':
                num = st.pop()
                st.push(st.pop() - num)
                break
            case '*':
                num = st.pop()
                st.push(st.pop() * num)
                break
            case '/':
                num = st.pop()
                st.push(Math.trunc(st.pop() / num))
                break
            default:
                st.push(Number(token))
        }
    })
    return st[0]
};