Given a string s
which represents an expression, evaluate this expression and return its value. 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^31, 2^31 - 1]
.
Note:
eval()
.Example 1:
Input: s = "3+2*2"
Output: 7
Example 2:
Input: s = " 3/2 "
Output: 1
Example 3:
Input: s = " 3+5 / 2 "
Output: 5
+
), subtraction (-
), multiplication (*
), and division (/
).To evaluate the expression, we will use the following approach:
current number
and an operation
.+
, -
, *
, /
).def calculate(s: str) -> int:
if not s:
return 0
stack = []
current_number = 0
operation = '+'
length = len(s)
for i in range(length):
char = s[i]
if char.isdigit():
current_number = current_number * 10 + int(char)
# if the char is not a digit and is not a space, or it is the end of the string
if (not char.isdigit() and char != ' ') or i == length - 1:
if operation == '+':
stack.append(current_number)
elif operation == '-':
stack.append(-current_number)
elif operation == '*':
stack[-1] = stack[-1] * current_number
elif operation == '/':
stack[-1] = int(stack[-1] / current_number)
operation = char
current_number = 0
return sum(stack)
# Examples
print(calculate("3+2*2")) # Output: 7
print(calculate(" 3/2 ")) # Output: 1
print(calculate(" 3+5 / 2 ")) # Output: 5
The time complexity of this solution is (O(n)), where (n) is the length of the string. This is because we are iterating over the string once and performing constant-time operations within the loop.
The space complexity of this solution is (O(n)) due to the stack, which in the worst case, can store up to all the numbers from the expression.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?