Problem Link
https://leetcode.com/problems/evaluate-reverse-polish-notation/
Detailed Step-by-Step Explanation
Solution
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 res = operate(a, b, token);
stack.push(res);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
private int operate(int a, int b, String token) {
switch (token) {
case "+" : return a + b;
case "-" : return a - b;
case "*" : return a * b;
case "/" : return a / b;
default : return 0;
}
}
}

Top comments (0)