美文网首页
剑指 Offer II 036. 后缀表达式

剑指 Offer II 036. 后缀表达式

作者: 邦_ | 来源:发表于2022-06-10 11: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!
        }
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:剑指 Offer II 036. 后缀表达式

          本文链接:https://www.haomeiwen.com/subject/igosertx.html