和力扣 224. 基本计算器 相同
class Solution {
private int i = 0;
public int solve(String s) {
//数据预处理:去除所有空格
s = s.replaceAll(" ", "");
return calculate(s);
}
public int calculate(String s) {
//s = s.replaceAll(" ", ""); //因为有递归,每次递归都做处理会耗时很久
//每个递归栈帧中都有自己独享的变量 num, sign, stack
int num = 0;
char sign = '+';
Stack<Integer> stack = new Stack<>();
for (;i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) num = num * 10 + (c - '0');
if (c == '(') {
i++;
num = calculate(s); //出现左括号就递归
}
if (!Character.isDigit(c) || i == s.length() - 1) {
switch(sign) {
case '+':
stack.push(num);
break;
case '-':
stack.push(-num);
break;
case '*':
stack.push(stack.pop() * num);
break;
case '/':
stack.push(stack.pop() / num);
break;
}
num = 0;
sign = c;
if (c == ')') break; //出现右括号就结束当前 for 循环
}
}
int res = 0;
while (!stack.isEmpty()) res += stack.pop(); //将当前递归帧中栈内剩余数字相加
return res;
}
}