Skip to content

Commit

Permalink
--
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb committed May 19, 2024
1 parent 8dc9435 commit 79c6665
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 2 deletions.
47 changes: 46 additions & 1 deletion content/posts/problems/basic-calculator-iii.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ math: true

# [772. Basic Calculator III](https://leetcode.com/problems/basic-calculator-iii)

[Solve on LintCode](https://www.lintcode.com/problem/849/)

## Description

Expand Down Expand Up @@ -61,4 +62,48 @@ math: true

## Solutions

<!-- end -->
[**Read: Solving Basic Calculator I, II, III on leetcode**](https://medium.com/@CalvinChankf/solving-basic-calculator-i-ii-iii-on-leetcode-74d926732437)

### Approach 1:
[SAME as Basic Calculator I Approach 1](/posts/basic-calculator/#Approach 1)

{{< terminal title="Python Code" >}}
```python
import collections
class Solution:
def calculate(self, s: str) -> int:
def helper(q):
stack = []
sign = '+'
num = 0
while q:
c = q.popleft()
if c.isdigit():
num = num*10 + int(c)
if c == '(':
num = helper(q)
if c in '+-*/)' or not q:
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack.append(stack.pop() * num)
elif sign == '/':
stack.append(int(stack.pop()/num))
sign = c
num = 0
if c == ')':
break
return sum(stack)


q = collections.deque()
for c in s:
q.append(c)
return helper(q)
```
{{< /terminal >}}

**Time**: O(N)
**Space**: O(N)
40 changes: 39 additions & 1 deletion content/posts/problems/basic-calculator.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,45 @@ After traversing the string $s$, we return $ans$.

The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the string $s$.

<!-- tabs:start -->
#### Approach 1:
**The below can be used in Basic Calculator III**

{{< terminal title="Python Code" >}}
```python
import collections
class Solution:
def calculate(self, s: str) -> int:
def helper(q):
stack = []
sign = '+'
num = 0
while q:
c = q.popleft()
if c.isdigit():
num = num*10 + int(c)
if c == '(':
num = helper(q)
if c in '+-)' or not q:
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
sign = c
num = 0
if c == ')':
break
return sum(stack)

q = collections.deque()
for c in s:
q.append(c)

return helper(q)
```
{{< /terminal >}}

**Time**: O(N)
**Space**: O(N)

{{< terminal title="Python Code" >}}
```python
Expand Down

0 comments on commit 79c6665

Please sign in to comment.