Question:
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
Thoughts:
A stack is needed to record operands and sub-results of the reverse polish notation
Scan the given postfix expression from left to right for each symbol { if operand then push onto stack if operator then { operand1=pop stack operand2=pop stack compute operand1 operator operand2 push result onto stack } } return top of stack as result
If the question asks to evaluate a polish notation(prefix notation), do the same process as the post-fix expression, but scan the expression from right to left.
public class Solution { public int evalRPN(String[] tokens) { if (tokens.length <= 0) { return 0; } LinkedList<String> stack = new LinkedList<String>(); String operators = "+-*/"; for (String s : tokens) { if (!operators.contains(s)) { stack.push(s); } else { int num1 = Integer.parseInt(stack.pop()); int num2 = Integer.parseInt(stack.pop()); if (s.equals("+")) stack.push(new Integer(num1 + num2).toString()); else if (s.equals("-")) stack.push(new Integer(num2 - num1).toString()); else if (s.equals("*")) stack.push(new Integer(num1 * num2).toString()); else if (s.equals("/")) stack.push(new Integer(num2 / num1).toString()); } } return Integer.parseInt(stack.pop()); } }