码迷,mamicode.com
首页 > 其他好文 > 详细

Evaluate Reverse Polish Notation——LeetCode

时间:2015-05-05 23:46:55      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

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

 

题目大意:给定一个String数组,数据是一个后缀表达式,求这个表达式的值。

解题思路:用栈来保存操作数即可,遇到数就入栈,遇到操作符就从栈里取出两个元素运算然后入栈即可,最后栈里只剩一个元素就是结果。这个不带括号还容易一点,直接上代码。

  static Map<String, Integer> op = new HashMap<>();

    static {
        op.put("+", 1);
        op.put("-", 2);
        op.put("*", 3);
        op.put("/", 4);
    }

    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0) {
            return 0;
        }
        Stack<Integer> nums = new Stack<>();
        for (String s : tokens) {
            if (op.get(s) != null) {
                int fa = nums.pop();
                int fb = nums.pop();
                if (op.get(s) == 1) {
                    nums.push(fb + fa);
                } else if (op.get(s) == 2) {
                    nums.push(fb - fa);
                } else if (op.get(s) == 3) {
                    nums.push(fb * fa);
                } else {
                    nums.push(fb / fa);
                }
            } else {
                nums.push(Integer.valueOf(s));
            }
        }
        return nums.peek();
    }

 

Evaluate Reverse Polish Notation——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4480605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!