You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation (RPN).
Evaluate the expression and return an integer that represents the value of the expression.
Note:
+, -, *, and /Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = 22
Reverse Polish Notation (postfix notation) is a mathematical notation where operators follow their operands. For example:
(2 + 1) * 32 1 + 3 *The beauty of RPN is that it doesn't require parentheses and can be evaluated using a stack in a single left-to-right scan.
Algorithm:
This is a classic Stack problem with these characteristics:
left op rightOrder Matters: When popping for operators, remember:
right = stack.pop()
left = stack.pop()
result = left op right // NOT right op left
1class Solution {
2 public int evalRPN(String[] tokens) {
3 Stack<Integer> stack = new Stack<>();
4
5 for (String token : tokens) {
6 if (isOperator(token)) {
7 // Pop two operands (order matters!)
8 int right = stack.pop();
9 int left = stack.pop();
10
11 // Apply operator and push result
12 int result = applyOperator(left, right, token);
13 stack.push(result);
14 } else {
15 // It's a number, push to stack
16 stack.push(Integer.parseInt(token));
17 }
18 }
19
20 // Final result is the only element in stack
21 return stack.pop();
22 }
23
24 private boolean isOperator(String token) {
25 return token.equals("+") || token.equals("-") ||
26 token.equals("*") || token.equals("/");
27 }
28
29 private int applyOperator(int left, int right, String operator) {
30 switch (operator) {
31 case "+": return left + right;
32 case "-": return left - right;
33 case "*": return left * right;
34 case "/": return left / right; // Integer division (truncates toward zero)
35 default: throw new IllegalArgumentException("Invalid operator");
36 }
37 }
38}
39