Optimal: value stack
Time O(n) Space O(n)Push numbers. For an operator, pop b then a, push a op b. The final value is the answer.
tokens = [2, 1, +, 3, *]stack(stack)
Step 1/4Push 2 and 1.
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> st = new ArrayDeque<>();
for (String t : tokens) {
switch (t) {
case "+" -> st.push(st.pop() + st.pop());
case "*" -> st.push(st.pop() * st.pop());
case "-" -> { int b = st.pop(), a = st.pop(); st.push(a - b); }
case "/" -> { int b = st.pop(), a = st.pop(); st.push(a / b); }
default -> st.push(Integer.parseInt(t));
}
}
return st.pop();
}
}Verdict: One pass.