forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EvaluateReversePolishNotation.swift
44 lines (39 loc) · 1.3 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
38
39
40
41
42
43
44
/**
* 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 {
guard let postNum = stack.popLast(), let prevNum = stack.popLast() else {
fatalError("Invalid Input")
}
stack.append(operate(token, prevNum, postNum))
}
}
if let last = stack.last {
return last
} else {
fatalError("Invalid Input")
}
}
private func operate(_ token: String, _ prevNum: Int, _ postNum: Int) -> Int {
switch token {
case "+":
return prevNum + postNum
case "-":
return prevNum - postNum
case "*":
return prevNum * postNum
case "/":
return prevNum / postNum
default:
fatalError("Invalid Input")
}
}
}