Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int calculate(String s) {
- Deque<Integer> nums = new LinkedList<>();
- Deque<Character> ops = new LinkedList<>();
- int i = 0, n = s.length(), v = -1;
- char[] c = s.toCharArray();
- while(i < n)
- {
- char ch = c[i];
- if(ch == ' '){} // skip white space
- else if(ch == '(')
- {
- int count = 1, j = i;
- while(count > 0)
- {
- j++;
- if(c[j] == '(') count++;
- if(c[j] == ')') count--;
- }
- // now j points to position after )
- nums.push(calculate(s.substring(i + 1, j))); // get direct result
- i = j;
- }
- else if('0' <= ch && ch <= '9')
- {
- if(v < 0) v = 0;
- v = v * 10 + ch - '0';
- }
- else // ch is operator
- {
- if(v >= 0) nums.push(v);
- v = -1;
- ops.push(ch);
- }
- i++;
- }
- if(v >= 0) nums.push(v);
- // System.out.println(nums);
- // System.out.println(ops);
- while(ops.size() > 0)
- {
- int a = nums.pollLast(), b = nums.pollLast();
- char ch = ops.pollLast();
- if(ch == '+') nums.offerLast(a + b);
- else nums.offerLast(a - b);
- // System.out.println(nums);
- }
- // System.out.println(nums);
- return nums.pop();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement