Thursday, May 29, 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

[Notes]:
这道题默认不用check input, 我加了个check stack的size() 对lc来说是多余的
有两个比较容易犯错误的点:
1, stack中存的是integer, 每次push记得convert一下。
2, stack pop( )的顺序和实际是反的,“+”和“*”操作没有影响,但“-”和“/”要注意下。

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

No comments:

Post a Comment