




Sponsored
Sponsored
The stack-based approach is ideal for evaluating Reverse Polish Notation (RPN) expressions because it naturally follows the Last-In-First-Out (LIFO) principle, which aligns with the evaluation order of RPN expressions. The key idea is to iterate through the tokens, pushing operands onto the stack, and handling operators by popping the required number of operands from the stack, performing the operation, and pushing the result back onto the stack.
Time Complexity: O(n), where n is the number of tokens.
Space Complexity: O(n) due to stack usage.
1import java.util.*;
2
3public class Solution {
4    public int evalRPN(String[] tokens) {
5        Stack<Integer> stack = new Stack<>();
6        for (String token : tokens) {
7            if ("+-*/".contains(token)) {
8                int b = stack.pop();
9                int a = stack.pop();
10                switch (token) {
11                    case "+": stack.push(a + b); break;
12                    case "-": stack.push(a - b); break;
13                    case "*": stack.push(a * b); break;
14                    case "/": stack.push(a / b); break;
15                }
16            } else {
17                stack.push(Integer.parseInt(token));
18            }
19        }
20        return stack.pop();
21    }
22}
23This solution uses a Stack data structure to store intermediate results. It sequentially processes each token, performing numeric conversions, stack manipulations, and arithmetic operations as applicable, until evaluating the entire expression.