1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| // 计算逆波兰表达式 class Solution { func evalRPN(_ tokens: [String]) -> Int { var stack: [Int] = [] for token in tokens { if isOperator(token: token) { let right = stack.popLast()! let left = stack.popLast()! let result = calculate(right: right, left: left, token: token) stack.append(result) } else { stack.append(Int(token)!) } } return stack.first! } func calculate(right: Int, left: Int, token: String) -> Int { if token == "+" { return left + right } else if token == "-" { return left - right } else if token == "*" { return left * right } else if token == "/" { return left / right } return 0 } func isOperator(token: String) -> Bool { return token == "+" || token == "-" || token == "*" || token == "/" } }
let solution = Solution() let array = ["-78","-33","196","+","-19","-","115","+","-","-99","/","-18","8","*","-86","-","-","16","/","26","-14","-","-","47","-","101","-","163","*","143","-","0","-","171","+","120","*","-60","+","156","/","173","/","-24","11","+","21","/","*","44","*","180","70","-40","-","*","86","132","-84","+","*","-","38","/","/","21","28","/","+","83","/","-31","156","-","+","28","/","95","-","120","+","8","*","90","-","-94","*","-73","/","-62","/","93","*","196","-","-59","+","187","-","143","/","-79","-89","+","-"] let result = solution.evalRPN(array) print(result)
|