1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution { public int calculate(String s) { s =s.replaceAll(" ",""); Deque<Integer> stack = new ArrayDeque<>(); char flag = '+'; int num = 0; for(int i=0;i<s.length();i++){ if(Character.isDigit(s.charAt(i))){ num = num*10+s.charAt(i)-'0'; } if(!Character.isDigit(s.charAt(i)) || i==s.length()-1){ if(flag=='+'){ stack.push(num); }else if(flag=='-'){ stack.push(-num); }else if(flag=='*'){ stack.push(stack.pop()*num); }else if(flag=='/'){ stack.push(stack.pop()/num); } flag = s.charAt(i); num =0; }
} int res =0; while(!stack.isEmpty()){ res += stack.pop(); }
return res;
} }
|