您的位置:首页 > 编程语言 > Lua

LeetCode:Evaluate Reverse Polish Notation (Java)

2014-08-06 01:09 573 查看

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 {
    private Set<String> set = new HashSet<String>();
    {                                                 //初始化块
        set.add("+");
        set.add("-");
        set.add("*");
        set.add("/");
    }

    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        int num1,num2 = 0;
        for(int i=0;i<tokens.length;i++) {
            if(!set.contains(tokens[i])) {
                stack.push(Integer.parseInt(tokens[i]));
            } else {
                num2 = stack.pop();
                num1 = stack.pop();
                stack.push(calculate(tokens[i].charAt(0), num1, num2));
            }
        }
        return stack.pop();
    }
    
    private int calculate(char operator, int num1, int num2) {
        switch(operator) {
            case '+':
                return num1 + num2;
            case '-':
                return num1 - num2;
            case '*':
                return num1 * num2;
            case '/':
                return num1 / num2;
            default:
                return 0;
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: