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 [-2³¹, 2³¹ - 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: 2Example 2:
Input: s = "6-4/2"
Output: 4Example 3:
Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21Constraints:
1 <= s <= 10⁴s consists of digits, '+', '-', '*', '/', '(', and ')'.s is a valid expression.class Solution:
def calculate(self, s: str) -> int:
def evaluate(x, y, operator):
if operator == "+":
return x
if operator == "-":
return -x
if operator == "*":
return x * y
return int(x / y)
stack = []
curr = 0
previous_operator = "+"
s += "@"
for c in s:
if c.isdigit():
curr = curr * 10 + int(c)
elif c == "(":
stack.append(previous_operator)
previous_operator = "+"
else:
if previous_operator in "*/":
stack.append(evaluate(stack.pop(), curr, previous_operator))
else:
stack.append(evaluate(curr, 0, previous_operator))
curr = 0
previous_operator = c
if c == ")":
while type(stack[-1]) == int:
curr += stack.pop()
previous_operator = stack.pop()
return sum(stack)Where is the length of the expression
class Solution:
def calculate(self, s: str) -> int:
def evaluate(x, y, operator):
if operator == "+":
return x
if operator == "-":
return -x
if operator == "*":
return x * y
return int(x / y)
def solve(i):
stack = []
curr = 0
previous_operator = "+"
while i[0] < len(s):
c = s[i[0]]
if c == "(":
i[0] += 1
curr = solve(i)
elif c.isdigit():
curr = curr * 10 + int(c)
else:
if previous_operator in "*/":
stack.append(evaluate(stack.pop(), curr, previous_operator))
else:
stack.append(evaluate(curr, 0, previous_operator))
if c == ")":
break
curr = 0
previous_operator = c
i[0] += 1
return sum(stack)
s += "@"
return solve([0])Where is the length of the expression