DEV Community

Debesh P.
Debesh P.

Posted on

150. Evaluate Reverse Polish Notation | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/evaluate-reverse-polish-notation/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/evaluate-reverse-polish-notation/solutions/7572013/most-optimal-solution-beats-500-stack-al-nrde


leetcode 150


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;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)