

方法
class Solution {
public int calculate(String s) {
int res = 0;
Stack<Integer> stack = new Stack<>();
char[] arr = s.toCharArray();
int val = 0;
char op = '+';
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
if (c == '(') {
int count = 1;
int cur = i + 1;
while (count != 0) {
if (arr[cur] == ')') {
count--;
}
if (arr[cur] == '(') {
count++;
}
cur++;
}
val = calculate(s.substring(i + 1, cur - 1));
i = cur - 1;
}
if (Character.isDigit(c)) {
val = val * 10 + c - '0';
}
if (!Character.isDigit(c) || i == arr.length - 1) {
if (op == '+') {
stack.push(val);
} else if (op == '-') {
stack.push(-val);
} else if (op == '*') {
stack.push(stack.pop() * val);
} else if (op == '/') {
stack.push(stack.pop() / val);
}
val = 0;
op = c;
}
}
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
}