150.逆波兰表达式求值(栈M)

/**
 * @param {string[]} tokens
 * @return {number}
 */
 var evalRPN = function(tokens) {
    let stack = []
    let set = new Set(['+','-','*','/'])
    for(let i = 0;i<tokens.length;i++){
        if(!set.has(tokens[i])){
            stack.push(parseInt(tokens[i]))
            continue
        }
        let num0 = parseInt(stack.pop())
        let num1 = parseInt(stack.pop())
        switch(tokens[i]){
            case '+':
                stack.push(num1 + num0)
                break
            case '-':
                stack.push(num1 - num0)
                break
            case '*':
                stack.push(num1 * num0)
                break
            case '/':
                stack.push(num1 / num0)
                break
        }
    }
    return parseInt(stack.pop())
}

 

posted @ 2021-04-09 13:55  心中有一海  阅读(44)  评论(0编辑  收藏  举报