Problem
Given an array of strings tokens representing an arithmetic expression in Reverse Polish Notation, evaluate the expression and return the integer result.The valid operators are
+, -, *, and /. Division between two integers truncates toward zero.
Example(s)
Consider the following examples to understand the expected input and output.Example 1
Input
tokens = ["2", "1", "+", "3", "*"]
Output
9
Example 2
Input
tokens = ["4", "13", "5", "/", "+"]
Output
6
Example 3
Input
tokens = ["10", "6", "9", "3", "/", "-", "*", "17", "+", "5", "+"]
Output
22
Solution
This solution uses a Stack to evaluate the Reverse Polish Notation expression.When we encounter a number, we push it onto the stack. When we encounter an operator, we pop the two most recent numbers, perform the operation, and push the result back onto the stack.
For an operator, the first value popped is the right operand and the second value popped is the left operand. This is important for subtraction and division.
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
if (isOperator(s)) {
int right = stack.pop();
int left = stack.pop();
stack.push(operation(left, right, s));
} else {
stack.push(Integer.parseInt(s));
}
}
return stack.pop();
}
private boolean isOperator(String s) {
return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
}
private int operation(int left, int right, String operator) {
return switch (operator) {
case "+" -> left + right;
case "-" -> left - right;
case "*" -> left * right;
case "/" -> left / right; // Java integer division truncates toward zero
default -> throw new IllegalArgumentException("Invalid operator: " + operator);
};
}
}
Complexity
Each token is processed exactly once. Therefore, the time complexity isO(n), where n is the number of tokens.
The stack can contain up to
n values in the worst case, so the extra space complexity is O(n).
Comments
No comments yet. Ask a question or share what helped.