[leedcode 150] 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 {
    //对于逆波兰式,一般都是用栈来处理,依次处理字符串,

    //如果是数值,则push到栈里面

    //如果是操作符,则从栈中pop出来两个元素,计算出值以后,再push到栈里面,

    //则最后栈里面剩下的元素即为所求。
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack=new Stack<Integer>();
        for(int i=0;i<tokens.length;i++){
            if(!isDigit(tokens[i])){
                stack.push(Integer.parseInt(tokens[i]));
                continue;
            }
            int num1=stack.pop();
            int num2=stack.pop();
            if(tokens[i].equals("-")){
                stack.push(num2-num1);
            }
            if(tokens[i].equals("+")){
                stack.push(num1+num2);
            }
            if(tokens[i].equals("*")){
                stack.push(num1*num2);
            }
            if(tokens[i].equals("/")){
                stack.push(num2/num1);
            }
        }
        return stack.pop();
    }
    public boolean isDigit(String s){
        if(s.equals("-")||s.equals("+")||s.equals("*")||s.equals("/")) return true;
        return false;
    }
}

 

posted @ 2015-08-01 20:51  ~每天进步一点点~  阅读(129)  评论(0编辑  收藏  举报