千问 LeetCode 224. Basic Calculator Java Implement
This is a classic stack sign tracking problem. The key insight is that parentheses only change the sign context — we don’t need to evaluate sub-expressions separately, just propagate the current sign into nested scopes.Core IdeaMaintain three things while scanning left to right:result: the accumulated sum so farsign: the current sign (1 or -1) for the next numberstack: stores the result and sign before each (, so we can restore them at )When we hit (, we push the current context and start fresh. When we hit ), we pop and merge the sub-result back.Java Implementationimport java.util.Deque;import java.util.ArrayDeque;class Solution {public int calculate(String s) {Deque stack new ArrayDeque();int result 0; // accumulated resultint sign 1; // current sign: 1 or -1int num 0; // current number being builtfor (int i 0; i s.length(); i) { char c s.charAt(i); if (Character.isDigit(c)) { num num * 10 (c - 0); } else if (c ) { result sign * num; num 0; sign 1; } else if (c -) { result sign * num; num 0; sign -1; } else if (c () { // Push current result and sign, then reset stack.push(result); stack.push(sign); result 0; sign 1; } else if (c )) { // Finish the number inside parentheses result sign * num; num 0; // Pop sign and previous result, merge result * stack.pop(); // sign before ( result stack.pop(); // result before ( } // spaces are ignored } // Dont forget the last number result sign * num; return result; }}Walkthrough with (1-(4-52)-3)Step Char Action result sign stack( push context 0 1 [0, 1]1 build num 0 1 [0, 1]result 1×1 1 -1 [0, 1]( push 0 1 [0,1, 1,-1]4 build 0 1 …result 1×4 4 -1 …5 build 4 -1 …result (-1)×5 -1 1 …2 build -1 1 …) result 1×21; ×(-1)-1; 10 0 — [0,1]result (-1)×0 0 -1 [0,1]3 build 0 -1 [0,1]end result (-1)×3 -3ComplexityTime: O(n) — single passSpace: O(d) where d is the max nesting depth of parenthesesKey Interview PointsWhy not recursion? Recursion works too (each ( spawns a recursive call), but the iterative stack approach avoids call-stack overhead and is easier to reason about in interviews.Why use Deque instead of Stack? Stack is a legacy class with synchronized methods — ArrayDeque is the modern, faster choice.Common bug: Forgetting to process the last number after the loop ends. Always add sign * num at the end.Follow-up: If the interviewer asks about * and /, you’d need a two-stack approach (operator stack operand stack) or a precedence-based parser — that’s LeetCode 772 (Basic Calculator III).Want me to also show the recursive version? It’s cleaner to read and sometimes easier to explain verbally in an interview.