这行代码是效率的关键
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!
}
网友评论