首页 > 其他 > 详细

leetcode: Evaluate Reverse Polish Notation

时间:2016-07-13 02:24:31      阅读:234      评论: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

原问题链接:https://leetcode.com/problems/evaluate-reverse-polish-notation/

?

问题分析

  关于逆波兰表达式的计算,其实是有固定的套路的。它和我们平常的表达式计算不一样,我们一般表达式里,计算符是放在两个操作数的中间,而这里计算符是放在两个操作数的后面。但是这个问题的解决思路还是比较简单的,我们每次碰到数字的时候就将它压入栈中,碰到计算符号时就将栈顶的两个元素弹出来参与计算,并将计算后的结果放到栈里面。

  按照这个思路,可以很容易得到如下的代码:

?

public class Solution {
    public int evalRPN(String[] tokens) {
        LinkedList<Integer> stack = new LinkedList<>();
        for(String str : tokens) {
            if(str.equals("+")) {
                stack.push(stack.pop() + stack.pop());
            } else if(str.equals("-")) {
                int second = stack.pop();
                stack.push(stack.pop() - second);
            } else if(str.equals("*")) {
                int result = stack.pop() * stack.pop();
                stack.push(result);
            } else if(str.equals("/")) {
                int second = stack.pop();
                stack.push(stack.pop() / second);
            } else {
                stack.push(Integer.parseInt(str));
            }
        }
        return stack.peek();
    }
}

?

leetcode: Evaluate Reverse Polish Notation

原文:http://shmilyaw-hotmail-com.iteye.com/blog/2310239

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!