forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EvaluateReversePolishNotation.swift
37 lines (32 loc) · 1.04 KB
/
EvaluateReversePolishNotation.swift
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
/**
* Question Link: https://leetcode.com/problems/evaluate-reverse-polish-notation/
* Primary idea: Push a number to a stack and pop two for operation when encounters a operator
* Time Complexity: O(n), Space Complexity: O(n)
*/
class EvaluateReversePolishNotation {
func evalRPN(_ tokens: [String]) -> Int {
var stack = [Int]()
for token in tokens {
if let num = Int(token) {
stack.append(num)
} else {
let post = stack.removeLast()
let prev = stack.removeLast()
stack.append(operate(prev, post, token))
}
}
return stack.first ?? 0
}
fileprivate func _operate(_ prev: Int, _ post: Int, _ token: String) -> Int{
switch token {
case "+":
return prev + post
case "-":
return prev - post
case "*":
return prev * post
default:
return prev / post
}
}
}