forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request soapyigu#281 from pepsikirk/master
[Stack] Add a solution to Basic Calculator
- Loading branch information
Showing
2 changed files
with
35 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
} | ||
} |