package com.zerroi.leetcode.Three22; import java.util.Deque; import java.util.LinkedList; import java.util.Stack; public class EvalRPN { public static void main(String[] args) { SolutionFirst solutionFirst = new SolutionFirst(); // int res = solutionFirst.evalRPN(new String[]{"2", "1", "+", "3", "*"}); int res = solutionFirst.evalRPN(new String[]{"10","6","9","3","+","-11","*","/","*","17","+","5","+"}); System.out.println("res = " + res); } } class SolutionFirst { public int evalRPN(String[] tokens) { Stack stack = new Stack<>(); int n1 = 0, n2 = 0; for (String token : tokens) { switch (token) { case "+": n1 = stack.pop(); n2 = stack.pop(); stack.add(n1 + n2); break; case "-": n1 = stack.pop(); n2 = stack.pop(); stack.add(n2 - n1); break; case "*": n1 = stack.pop(); n2 = stack.pop(); stack.add(n1*n2); break; case "/": n1 = stack.pop(); n2 = stack.pop(); stack.add(n2 / n1); break; default: stack.add(Integer.valueOf(token)); break; } } return stack.isEmpty() ? 0 : stack.getFirst(); } }