Description
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 ``.
Example 1:
1 2
| Input: "1 + 1" Output: 2
|
Example 2:
1 2
| Input: " 2-1 + 2 " Output: 3
|
Example 3:
1 2
| Input: "(1+(4+5+2)-3)+(6+8)" Output: 23
|
Note:
####
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public int calculate(String s) { s = s.replaceAll("\\s+", ""); int cal = 0, o = 1; char[] exp = s.toCharArray(); Deque<Integer> stack = new ArrayDeque<>(); for (int i = 0; i < exp.length; i++){ switch(exp[i]){ case '(': stack.offerFirst(cal); stack.offerFirst(o); cal = 0; o = 1; break; case ')': cal = stack.poll() * cal + stack.poll(); break; case '+': case '-': o = exp[i] == '+' ? 1 : -1; break; default: int num = exp[i] - '0'; while(i + 1 < exp.length && Character.isDigit(exp[i + 1])) num = num * 10 + (exp[++i] - '0'); cal += o * num; } } return cal; }
|