forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EvaluateReversePolishNotation.swift
50 lines (43 loc) · 1.33 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
45
46
47
48
49
50
/**
* 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 str in tokens {
if _isNumber(str) {
stack.append(Int(str)!)
} else {
guard stack.count > 1 else {
return 0
}
let post = stack.removeLast()
let prev = stack.removeLast()
let res = _operate(prev, post, str)
stack.append(res)
}
}
if stack.count == 0 {
return 0
} else {
return stack.first!
}
}
private func _isNumber(str: String) -> Bool {
return Int(str) != nil
}
private 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
}
}
}