public int calculate(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
int sign = 1;
int n = s.length();
int num = 0;
int res = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
char cur = s.charAt(i);
if (Character.isDigit(cur)) {
num = num * 10 + Character.getNumericValue(cur);
} else if (cur == '+' || cur == '-') {
res += num * sign;
num = 0;
sign = cur == '+' ? 1 : -1;
} else if (cur == '(') {
stack.push(res);
stack.push(sign);
res = 0;
sign = 1;
} else if (cur == ')') {
res += num * sign;
sign = stack.pop();
num = res;
res = stack.pop();
}
}
res += num * sign;
return res;
}