Friday, February 7, 2014

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

Solution:
The key to solve this question is what data structure are we going to choose. 
By observation, we will notice that each operator works on its previous two numbers. So we can use a stack, push number elements, when met an operator, pop up two numbers, and then push the result into the stack. 
Tips: String->Integer: Integer.parseInt(str).


public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<String>();
        if(tokens.length == 0) return 0;
        stack.push(tokens[0]);
        int i = 1;
        while(i < tokens.length){
            String str = tokens[i];
            if(isOperator(str)) {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                stack.push(Integer.toString(cacl(num1,num2,str)));
            }
            else{
                stack.push(str);
            }
            i++;
        }
        return Integer.parseInt(stack.pop());
    }
    public int cacl(int x, int y, String operator){
        if(operator.equals("+")) return x+y;
        else if(operator.equals("-")) return x-y;
        else if(operator.equals("*")) return x*y;
        return x/y;
    }
    public boolean isOperator(String s){
        return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/");
    }
}

No comments:

Post a Comment