LeetCode 0772. Basic Calculator III Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0772. Basic Calculator III

Description

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and open '(' and closing parentheses ')'. The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

 

Example 1:

Input: s = "1+1"
Output: 2

Example 2:

Input: s = "6-4/2"
Output: 4

Example 3:

Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21

 

Constraints:

  • 1 <= s <= 104
  • s consists of digits, '+', '-', '*', '/', '(', and ')'.
  • s is a valid expression.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def calculate(self, s: str) -> int: def dfs(q): num, sign, stk = 0, "+", [] while q: c = q.popleft() if c.isdigit(): num = num * 10 + int(c) if c == "(": num = dfs(q) if c in "+-*/)" or not q: match sign: case "+": stk.append(num) case "-": stk.append(-num) case "*": stk.append(stk.pop() * num) case "/": stk.append(int(stk.pop() / num)) num, sign = 0, c if c == ")": break return sum(stk) return dfs(deque(s))(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !