Leetcode 227. Basic Calculator II
Given a string s
which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero.
s
consists of integers and operators (+
, -
, *
, /
) separated by some number of spaces.+
, -
, *
, /
), and spaces.7 / -3
should be -2
).num
to build the current number as we iterate.sign
variable to keep track of the last seen operation (+
by default).When we encounter a number, we will continue building it until we encounter an operator or the end of the string.
sign
, we will process the previous number with the current number:
+
: Push the current number to the stack.-
: Push the negated current number to the stack.*
: Pop the top of the stack, multiply it by the current number, and push the result back./
: Pop the top of the stack, divide it by the current number, truncate toward zero, and push the result back.import java.util.Stack;
public class BasicCalculatorII {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
int num = 0;
char sign = '+';
s = s.replaceAll(" ", ""); // Remove all spaces
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
}
if (!Character.isDigit(c) || i == s.length() - 1) {
switch (sign) {
case '+':
stack.push(num);
break;
case '-':
stack.push(-num);
break;
case '*':
stack.push(stack.pop() * num);
break;
case '/':
stack.push(stack.pop() / num);
break;
}
sign = c;
num = 0;
}
}
int result = 0;
for (int number : stack) {
result += number;
}
return result;
}
public static void main(String[] args) {
BasicCalculatorII calc = new BasicCalculatorII();
System.out.println(calc.calculate("3+2*2")); // Output: 7
System.out.println(calc.calculate(" 3/2 ")); // Output: 1
System.out.println(calc.calculate(" 3+5 / 2 ")); // Output: 5
}
}
The time complexity of this solution is (O(n)), where (n) is the length of the input string. This is because we process each character in the string exactly once.
The space complexity is also (O(n)) in the worst case because we might store each number in the stack before summing them up.
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?