Skip to content

Commit c65138d

Browse files
authored
Merge pull request soapyigu#281 from pepsikirk/master
[Stack] Add a solution to Basic Calculator
2 parents 9251282 + 033fedd commit c65138d

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@
174174
[Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/)| [Swift](./Stack/BinarySearchTreeIterator.swift)| Medium| O(n)| O(n)|
175175
[Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/)| [Swift](./Stack/PostorderTraversal.swift)| Hard| O(n)| O(n)|
176176
[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)|
177178

178179
## Queue
179180
| Title | Solution | Difficulty | Time | Space |
@@ -689,7 +690,7 @@
689690
| | 227 | [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/) | Medium |
690691
| [Swift](./Tree/InvertBinaryTree.swift) | 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | Easy |
691692
| | 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 |
693694
| [Swift](./Math/RectangleArea.swift) | 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | Easy |
694695
| | 222 | [Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/) | Medium |
695696
| [Swift](./DP/MaximalSquare.swift) | 221 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | Medium |

Stack/BasicCalculator.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
}

0 commit comments

Comments
 (0)