Basic Calculator II
https://leetcode.com/problems/basic-calculator-ii/description/
class Solution {
public int calculate(String s) {
if(s == null || s.length() == 0){
return 0;
}
int len = s.length();
char sign = '+';
int num = 0;
Deque<Integer> stack = new LinkedList<>();
for(int i = 0; i < len; i++){
char cur = s.charAt(i);
if(Character.isDigit(cur)){
num = num * 10 + cur - '0';
}
// && precedence > ||
// When i == len - 1, the last value has not been added to the stack
// also the loop will stop, so we need to consider this corner case
if(!Character.isDigit(cur) && cur != ' ' || i == len - 1){
if(sign == '+'){
stack.push(num);
}
if(sign == '-'){
stack.push(-num);
}
if(sign == '*'){
stack.push(stack.pop() * num);
}
if(sign == '/'){
stack.push(stack.pop() / num);
}
sign = cur;
num = 0;
}
}
int res = 0;
for(Integer i : stack){
res += i;
}
return res;
}
}
Use stack to store the previous value for multiply and divide operations.