Evaluate Reverse Polish Notation

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


public class Solution {
    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0) {
        	return 0;
        }
        Stack<Integer> stack = new Stack<Integer>();
        for (String string : tokens) {
        	int res = 0;
        	if (string.equals("+") || string.equals("-") || string.equals("*") || string.equals("/")) {
        		int b = stack.pop();
        		int a = stack.pop();
        		if (string.equals("+")) {
        			res += (a + b);
        		} else if (string.equals("-")) {
        			res += (a - b);
        		} else if (string.equals("*")) {
        			res += (a * b);
        		} else {
        			res += (a / b);
        		}
        		stack.push(res);
        	} else {
        		stack.push(Integer.valueOf(string));
        	}
		}
        return stack.pop();
    }
}
 

你可能感兴趣的:(Evaluate Reverse Polish Notation)