150. Evaluate Reverse Polish Notation

https://leetcode.com/problems/evaluate-reverse-polish-notation/#/description

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

 

 RPN中文名字叫做逆波兰表示法,它的好处维基百科说了,就是不需要括号来表示运算的先后,直接根据式子本身就可以求解。解题思路就是维护一个栈,遇到数字就入栈,遇到操作符就两次出栈得到栈顶的两个操作数,运用操作符进行运算以后,再把结果入栈。直到式子结束,此时栈中唯一一个元素便是结果。

以上代码中有一个没有周全的地方是没有对逆波兰式错误的情况进行出错处理,其实也不难,就是每次pop操作检查栈空情况,如果栈空,则说明出错,throw an exception。还有就是最后检查一下栈的size,如果不是1也说明运算数多了,返回错误。

I add every token as an integer in the stack, unless it's an operation. In that case, I pop two elements from the stack and then save the result back to it. After all operations are done through, the remaining element in the stack will be the result.

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

Integer.parseInt()把 String 把 型转换为 Int 型, Integer.valueOf()把 String 把 对象. 型转换为 Integer 对象. 大概知道一点了, 是针对包装类来说的  

posted @ 2017-07-05 22:13  apanda009  阅读(152)  评论(0编辑  收藏  举报