forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicCalculator.swift
33 lines (30 loc) · 902 Bytes
/
BasicCalculator.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
/**
* Question Link: https://leetcode.com/problems/basic-calculator/
* Primary idea: Use a stack to save sign, then determines whether sign inversion is currently required
* Time Complexity: O(n), Space Complexity: O(n)
*/
class BasicCalculator {
func calculate(_ s: String) -> Int {
var result = 0
var num = 0
var sign = 1
var stack = [sign]
for char in s {
switch char {
case "+", "-":
result += num * sign
sign = stack.last! * (char == "+" ? 1 : -1)
num = 0
case "(":
stack.append(sign)
case ")":
stack.removeLast()
case " ":
break
default:
num = num * 10 + char.wholeNumberValue!
}
}
return result + num * sign
}
}