先做Leetcode 227再做本题
本题在227的基础上多了括号
题解
将 减法、乘法、除法 转换为 加法
某个数 num, 如果前面的对应的运算符是 -,那么 将 -num 压入栈中
这样,我们只需在最后将栈的元素全部弹出,完成加法操作,即可得到最终结果
对于括号,它存在递归性质
即
3 * (2 + 4 * 3) + 2
= 3 * calculate(2 + 4 * 3) + 2
= 3 * 24 + 2
即我们可以将括号内的字符串当作一个运算式,再递归调用本函数,最终返回一个数值
bash
class Solution {
int i=0;
public int calculate(String s) {
return calHelper(s);
}
public int calHelper(String s){
//数字num是和已有的运算符sign做计算
Stack<Integer> nums=new Stack<>();
//Stack<Character> ops=new Stack<>();
char[] str=s.toCharArray();
//对于第一个数字,其之前的运算符视为加号
char preSign = '+';
//记录当前数字大小
int num=0;
for(;i<str.length;i++){
char c=str[i];
//1.是数字
if(c>='0'&&c<='9'){
num=num*10+(c-'0');
}
// 2、如果为左括号,从左括号的下一个字符开始递归
else if(c == '(') {
i++;
num = calHelper(s);
}
//3.是符号或者遍历到了字符串末尾
if(!Character.isDigit(c) && s.charAt(i) != ' '||i == str.length-1){
switch(preSign){
case '+':
nums.push(num);break;
case '-':
nums.push(-num);break;
case '*':
nums.push(nums.pop()*num);break;
case '/':
nums.push(nums.pop()/num);break;
}
// 更新符号为当前符号,数字清零
preSign=c;
num=0;
}
// 4、如果为右括号,结束递归(返回后,i指向新生成的数字)
if(c == ')') {
//i++;
break;
}
}
// 将栈中所有结果求和就是答案
int res = 0;
while (!nums.isEmpty()) {
res += nums.pop();
}
return res;
}
}