总算找到这题正确的,便于理解的方法了。
iterative, stack, 括号
好好体会这三者到联系。
public int calculate(String s) {
s = s.replace(" ","");
int res = 0;
int sign = 1;
Stack
resStack = new Stack<>();
Stack
signs = new Stack<>();
int i = 0;
while(i
0){
res = res*signs.pop() + resStack.pop();
}
i++;
}
}
return res;
}
要是被考这种题目,也是醉了。太个例了。这个方法是我找到最简单的一种实现,也好理解,记住吧。以后再做不要浪费时间了。
核心思路(code ganker method):
我们只能加入之前的数,不能加之后的,因为我们不知道之后的会不会有乘法。遇到乘除更新之前的数,不然就向结果加入之前的数,然后更新之前的数为当前的数。这里要把正负记在数里,因为operator的信息接着会被抹掉。
以 2 - 3+3*3 为例
当扫到 ‘-‘,我们previous value是2, res + 2, 更新prev value
当扫到’+‘, 我们previous value是-3, res + (-3)更新 prev value
当扫到’*‘, 我们previous value是 3,更新之为 3*3
扫完了最后加上最后一个prev value res + 3*3
上面的方法代码简单但是思维逆向。是按照计算机的逻辑思考。
//update my version
public class Solution {
public int calculate(String s) {
s = s.replaceAll(" ","");
char[] sc = s.toCharArray();
HashSet
opts = new HashSet
();
opts.add('+');
opts.add('-');
opts.add('*');
opts.add('/');
Stack
stack = new Stack
();
int i = 0;
while(i
opts){ int res = s.charAt(i++) - '0'; while(i
=0){ cur_value = 10*cur_value + s.charAt(i) - '0'; i++; } if(prev_op == '+'){ res += prev_value; prev_value = cur_value; } if(prev_op == '-'){ //pay attention here. We can only add previous value to res safely, the previous value could be either positive //or negative. //Notice, the previous operator deicde current value to be positive or negative. //the previous previous operator decide previous value's positiveness. //when we deal previous value, we already override previous previous operator, that's why //we must incorporate its information into the value(current value at that time) when we still have it. res += prev_value; prev_value = -cur_value; } if(prev_op == '*'){ prev_value *= cur_value; } if(prev_op == '/'){ prev_value /= cur_value; } if(i < s.length()) prev_op = s.charAt(i); i++; } res += prev_value; return res; } }