224 Basic Calculator
224. Basic Calculator
1. Question
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 232. Implementation
class Solution {
public int calculate(String s) {
s.replace(" ", "");
int res = 0;
Stack<Integer> stack = new Stack<>();
stack.push(1);
int i = 0;
int sign = 1;
while (i < s.length()) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
int val = 0;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
val = 10 * val + s.charAt(i) - '0';
++i;
}
--i;
res += sign * val * stack.peek();
}
else if (c == '(') {
stack.push(sign * stack.peek());
sign = 1;
}
else if (c == ')') {
stack.pop();
}
else {
sign = c == '-' ? -1 : 1;
}
++i;
}
return res;
}
}3. Time & Space Complexity
Last updated