Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open
(
and closing parentheses )
, the plus +
or minus sign -
, non-negative integers and empty spaces
.
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
Note: Do not use the
eval
built-in library function.class Solution {
public int calculate(String s) {
if (s == null || s.isEmpty()) return 0;
Stack<Integer> stack = new Stack();
int sign = 1;
int number = 0;
int sum = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
number = number * 10 + ch - '0';
} else if (ch == '+') {
sum = sum + sign * number;
sign = 1;
number = 0;
} else if (ch == '-') {
sum = sum + sign * number;
sign = -1;
number = 0;
} else if (ch == '(') {
stack.push(sum);
stack.push(sign);
sum = 0;
sign = 1;
} else if (ch == ')') {
sum = sum + sign * number;
sum *= stack.pop();
sum += stack.pop();
number = 0;
}
}
sum = sum + sign * number;
return sum;
}
}
留言
張貼留言