LeetCode-Evaluate Reverse Polish Notation

因为是很标准的两个oprand 一个operator 所以很简单 

但是注意string compare不能用==!!!要用equals

外加注意-和/的顺序

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack <Integer> stack = new Stack <Integer> ();
        for ( int i = 0; i < tokens.length; i ++ ){
            if ( tokens[i].equals("+")){
                int op1 = stack.pop();
                int op2 = stack.pop();
                stack.push(op1 + op2);
            }
            else if ( tokens[i].equals("-") ){
                int op1 = stack.pop();
                int op2 = stack.pop();
                stack.push(op2 - op1);
            } 
            else if ( tokens[i].equals("*")){
                int op1 = stack.pop();
                int op2 = stack.pop();
                stack.push(op1 * op2);
            }
            else if ( tokens[i].equals("/") ){
                int op1 = stack.pop();
                int op2 = stack.pop();
                stack.push(op2 / op1);
            }
            else{
                stack.push( Integer.parseInt(tokens[i]));
            }
        }
        return stack.peek();
    }
}


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