=
stackoperands waiting
public int evalRPN(String[] tokens) { Deque<Integer> stack = new ArrayDeque<>(); for (String t : tokens) { if ("+-*/".contains(t)) { int b = stack.pop(); int a = stack.pop(); // right operand is on top if (t.equals("+")) { stack.push(a + b); } else if (t.equals("-")) { stack.push(a - b); } else if (t.equals("*")) { stack.push(a * b); } else { stack.push(a / b); // truncates toward 0 } } else { stack.push(Integer.parseInt(t)); } } return stack.peek();}
- t
- —
- a, b
- —
- stack
- []
- top means
- —
Why it works
- Brute force rewrites the list: find the first operator, replace it and its two operands with their result, and repeat. Each rewrite rescans and shifts the list: O(n²).
- Key insight: an operator always applies to the two most recent unused values. Most recent first is last in, first out: a stack. Invariant: the stack holds the values of the complete sub-expressions read so far, in order.
- O(n) time, O(n) space. Every token is pushed once, and every operator pops two and pushes one. A valid expression ends with exactly one value: the answer.
- Pitfall: operand order and division. The first pop is the right operand, so
3 4 -is3 - 4, not4 - 3. And division must truncate toward zero: Java's/onintalready does, so-7 / 2is -3 (Math.floorDivwould give -4). Compare tokens withequals, not==. Also,"-11"is a number, not an operator. - Related: Basic Calculator (224, 227) turns infix into this form on the fly with an operator stack; the shunting-yard algorithm is the general version.