




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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5    public int EvalRPN(string[] tokens) {
6        Stack<int> stack = new Stack<int>();
7        foreach (string token in tokens) {
8            if ("+-*/".Contains(token)) {
9                int b = stack.Pop();
10                int a = stack.Pop();
11                switch (token) {
12                    case "+": stack.Push(a + b); break;
13                    case "-": stack.Push(a - b); break;
14                    case "*": stack.Push(a * b); break;
15                    case "/": stack.Push(a / b); break;
16                }
17            } else {
18                stack.Push(int.Parse(token));
19            }
20        }
21        return stack.Pop();
22    }
23}
24C# solution leverages the in-built Stack class. For each token processed, it uses control structures for arithmetic operations and built-in methods to handle numerical data, following the RPN evaluation strategy.