You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
Note that:
Use a stack to evaluate the Reverse Polish Notation expression. Iterate through each token in the array. If the token is a number, push it onto the stack. If the token is an operator, pop the top two elements from the stack, apply the operation (with the first popped as the right operand and the second as the left), and push the result back onto the stack. At the end, the stack will contain the final result.
Example Input: tokens = [“2”,”1”,”+”,”3”,”*”]
Output: 9
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/")) {
int b = stack.pop();
int a = stack.pop();
int result;
switch (token) {
case "+":
result = a + b;
break;
case "-":
result = a - b;
break;
case "*":
result = a * b;
break;
default:
result = a / b;
break;
}
stack.push(result);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}