LeetCode 150. Evaluate Reverse Polish Notation

Problem:

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

Solution:

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<String> nums = new Stack<>();
        Stack<String> ops = new Stack<>();
        for (String token: tokens) {
            if (isOp(token)) {
                if (nums.isEmpty()) {
                    ops.push(token);
                }
                else {
                    String num1 = nums.pop();
                    String num2 = nums.pop();
                    int a = Integer.parseInt(num1);
                    int b = Integer.parseInt(num2);
                    if (token.equals("+")) {
                        nums.push(a + b + "");
                    }
                    else if (token.equals("-")) {
                        nums.push(b - a + "");
                    }
                    else if (token.equals("*")) {
                        nums.push(b * a + "");
                    }
                    else {
                        nums.push(b / a + "");
                    }
                }
            }
            else {
                nums.push(token);
            }
        }
        String last = nums.pop();
        return Integer.parseInt(last);
    }
    
    private boolean isOp(String s) {
        String ops = "+-*/";
        return ops.indexOf(s) > -1;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *