Approach
Stack-based processing
For Basic Calculator III, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 59 lines of Java from the credited upstream file 772.java.
- The implementation visibly relies on work queue.
- 5 loop blocks detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int calculate(String s) {3 Deque<Integer> nums = new ArrayDeque<>();4 Deque<Character> ops = new ArrayDeque<>();5 boolean hasPrevNum = false;6 7 for (int i = 0; i < s.length(); ++i) {8 final char c = s.charAt(i);9 if (Character.isDigit(c)) {10 int num = c - '0';11 while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1)))12 num = num * 10 + (s.charAt(i++ + 1) - '0');13 nums.push(num);14 hasPrevNum = true;15 } else if (c == '(') {16 ops.push('(');17 hasPrevNum = false;18 } else if (c == ')') {19 while (ops.peek() != '(')20 calc(nums, ops);21 ops.pop(); 22 } else if (c == '+' || c == '-' || c == '*' || c == '/') {23 if (!hasPrevNum)24 nums.push(0);25 while (!ops.isEmpty() && precedes(ops.peek(), c))26 calc(nums, ops);27 ops.push(c);28 }29 }30 31 while (!ops.isEmpty())32 calc(nums, ops);33 34 return nums.peek();35 }36 37 private void calc(Deque<Integer> nums, Deque<Character> ops) {38 final int b = nums.pop();39 final int a = nums.pop();40 final char op = ops.pop();41 if (op == '+')42 nums.push(a + b);43 else if (op == '-')44 nums.push(a - b);45 else if (op == '*')46 nums.push(a * b);47 else 48 nums.push(a / b);49 }50 51 52 53 private boolean precedes(char prev, char curr) {54 if (prev == '(')55 return false;56 return prev == '*' || prev == '/' || curr == '+' || curr == '-';57 }58}59