File tree Expand file tree Collapse file tree 2 files changed +35
-1
lines changed Expand file tree Collapse file tree 2 files changed +35
-1
lines changed Original file line number Diff line number Diff line change 174
174
[ Binary Search Tree Iterator] ( https://leetcode.com/problems/binary-search-tree-iterator/ ) | [ Swift] ( ./Stack/BinarySearchTreeIterator.swift ) | Medium| O(n)| O(n)|
175
175
[ Binary Tree Postorder Traversal] ( https://leetcode.com/problems/binary-tree-postorder-traversal/ ) | [ Swift] ( ./Stack/PostorderTraversal.swift ) | Hard| O(n)| O(n)|
176
176
[ Decode String] ( https://leetcode.com/problems/decode-string/ ) | [ Swift] ( ./Stack/DecodeString.swift ) | Medium| O(n)| O(n)|
177
+ [ Basic Calculator] ( https://leetcode.com/problems/basic-calculator/ ) | [ Swift] ( ./Stack/BasicCalculator.swift ) | Hard| O(n)| O(n)|
177
178
178
179
## Queue
179
180
| Title | Solution | Difficulty | Time | Space |
689
690
| | 227 | [ Basic Calculator II] ( https://leetcode.com/problems/basic-calculator-ii/ ) | Medium |
690
691
| [ Swift] ( ./Tree/InvertBinaryTree.swift ) | 226 | [ Invert Binary Tree] ( https://leetcode.com/problems/invert-binary-tree/ ) | Easy |
691
692
| | 225 | [ Implement Stack using Queues] ( https://leetcode.com/problems/implement-stack-using-queues/ ) | Easy |
692
- | | 224 | [ Basic Calculator] ( https://leetcode.com/problems/basic-calculator/ ) | Hard |
693
+ | [ Swift ] ( ./Stack/BasicCalculator.swift ) | 224 | [ Basic Calculator] ( https://leetcode.com/problems/basic-calculator/ ) | Hard |
693
694
| [ Swift] ( ./Math/RectangleArea.swift ) | 223 | [ Rectangle Area] ( https://leetcode.com/problems/rectangle-area/ ) | Easy |
694
695
| | 222 | [ Count Complete Tree Nodes] ( https://leetcode.com/problems/count-complete-tree-nodes/ ) | Medium |
695
696
| [ Swift] ( ./DP/MaximalSquare.swift ) | 221 | [ Maximal Square] ( https://leetcode.com/problems/maximal-square/ ) | Medium |
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/basic-calculator/
3
+ * Primary idea: Use a stack to save sign, then determines whether sign inversion is currently required
4
+ * Time Complexity: O(n), Space Complexity: O(n)
5
+ */
6
+
7
+ class BasicCalculator {
8
+ func calculate( _ s: String ) -> Int {
9
+ var result = 0
10
+ var num = 0
11
+ var sign = 1
12
+ var stack = [ sign]
13
+
14
+ for char in s {
15
+ switch char {
16
+ case " + " , " - " :
17
+ result += num * sign
18
+ sign = stack. last! * ( char == " + " ? 1 : - 1 )
19
+ num = 0
20
+ case " ( " :
21
+ stack. append ( sign)
22
+ case " ) " :
23
+ stack. removeLast ( )
24
+ case " " :
25
+ break
26
+ default :
27
+ num = num * 10 + char. wholeNumberValue!
28
+ }
29
+ }
30
+
31
+ return result + num * sign
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments