剑指 Offer II 036. 后缀表达式

2022-06-10  本文已影响0人  邦_

这行代码是效率的关键
stack.last!


func evalRPN(_ tokens: [String]) -> Int {
        var stack = Array<Int>()
        
        for s in tokens {
            
            if s == "+" {
                let num1 = stack.popLast() ?? 0
                let num2 = stack.popLast() ?? 0
                stack.append(num2 + num1)
            }else if s == "-" {
                let num1 = stack.popLast() ?? 0
                let num2 = stack.popLast() ?? 0
                stack.append(num2 - num1)
            }else if s == "*" {
                let num1 = stack.popLast() ?? 0
                let num2 = stack.popLast() ?? 0
                stack.append(num2 * num1)
            }else if s == "/" {
                let num1 = stack.popLast() ?? 0
                let num2 = stack.popLast() ?? 0
                stack.append(num2 / num1)
            }else {
                stack.append(Int(s)!)
            }
        }
        
        return stack.last!
    }







上一篇下一篇

猜你喜欢

热点阅读