Advertisement
lifeiteng

224. Basic Calculator

Sep 26th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. class Solution {
  2.     public int calculate(String s) {
  3.         Deque<Integer> nums = new LinkedList<>();
  4.         Deque<Character> ops = new LinkedList<>();
  5.         int i = 0, n = s.length(), v = -1;
  6.         char[] c = s.toCharArray();
  7.         while(i < n)
  8.         {
  9.             char ch = c[i];
  10.             if(ch == ' '){}   // skip white space
  11.             else if(ch == '(')
  12.             {
  13.                 int count = 1, j = i;
  14.                 while(count > 0)
  15.                 {
  16.                     j++;
  17.                     if(c[j] == '(') count++;
  18.                     if(c[j] == ')') count--;
  19.                 }
  20.                 // now j points to position after )
  21.                 nums.push(calculate(s.substring(i + 1, j)));    // get direct result
  22.                 i = j;
  23.             }
  24.             else if('0' <= ch && ch <= '9')
  25.             {
  26.                 if(v < 0) v = 0;
  27.                 v = v * 10 + ch - '0';
  28.             }
  29.             else    // ch is operator
  30.             {
  31.                 if(v >= 0) nums.push(v);
  32.                 v = -1;
  33.                 ops.push(ch);
  34.             }
  35.             i++;
  36.         }
  37.         if(v >= 0) nums.push(v);
  38.        
  39.         // System.out.println(nums);
  40.         // System.out.println(ops);
  41.        
  42.         while(ops.size() > 0)
  43.         {
  44.             int a = nums.pollLast(), b = nums.pollLast();
  45.             char ch = ops.pollLast();
  46.             if(ch == '+') nums.offerLast(a + b);
  47.             else nums.offerLast(a - b);
  48.             // System.out.println(nums);            
  49.         }
  50.        
  51.         // System.out.println(nums);
  52.         return nums.pop();
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement