Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. For example:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

1. Naive Approach

This problem can be solved by using a stack. We can loop through each element in the given array. When it is a number, push it to the stack. When it is an operator, pop two numbers from the stack, do the calculation, and push back the result.

public class Test {

	public static void main(String[] args) throws IOException {
		String[] tokens = new String[] { "2", "1", "+", "3", "*" };
		System.out.println(evalRPN(tokens));
	}

	public static int evalRPN(String[] tokens) {
		int returnValue = 0;
		String operators = "+-*/";

		Stack<String> stack = new Stack<String>();

		for (String t : tokens) {
			if (!operators.contains(t)) { //push to stack if it is a number
				stack.push(t);
			} else {//pop numbers from stack if it is an operator
				int a = Integer.valueOf(stack.pop());
				int b = Integer.valueOf(stack.pop());
				switch (t) {
				case "+":
					stack.push(String.valueOf(a + b));
					break;
				case "-":
					stack.push(String.valueOf(b - a));
					break;
				case "*":
					stack.push(String.valueOf(a * b));
					break;
				case "/":
					stack.push(String.valueOf(b / a));
					break;
				}
			}
		}

		returnValue = Integer.valueOf(stack.pop());

		return returnValue;
	}
}

or

public class Solution {
    public int evalRPN(String[] tokens) {

        int returnValue = 0;

        String operators = "+-*/";

        Stack<String> stack = new Stack<String>();

        for(String t : tokens){
            if(!operators.contains(t)){
                stack.push(t);
            }else{
                int a = Integer.valueOf(stack.pop());
                int b = Integer.valueOf(stack.pop());
                int index = operators.indexOf(t);
                switch(index){
                    case 0:
                        stack.push(String.valueOf(a+b));
                        break;
                    case 1:
                        stack.push(String.valueOf(b-a));
                        break;
                    case 2:
                        stack.push(String.valueOf(a*b));
                        break;
                    case 3:
                        stack.push(String.valueOf(b/a));
                        break;
                }
            }
        }

        returnValue = Integer.valueOf(stack.pop());

        return returnValue;

    }
}

[算法]Evaluate Reverse Polish Notation的更多相关文章

  1. LeetCode 150. 逆波兰表达式求值(Evaluate Reverse Polish Notation) 24

    150. 逆波兰表达式求值 150. Evaluate Reverse Polish Notation 题目描述 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, /.每个运算对象 ...

  2. 【leetcode】Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation 题目描述: Evaluate the value of an arithmetic expression in Reverse Pol ...

  3. [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  4. LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation

    LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation Evaluate the value of an arithm ...

  5. 【LeetCode练习题】Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...

  6. leetcode - [2]Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation Total Accepted: 24595 Total Submissions: 123794My Submissions Evalu ...

  7. 【LeetCode】150. Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...

  8. LeetCode: Evaluate Reverse Polish Notation 解题报告

    Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...

  9. 【LeetCode】150. Evaluate Reverse Polish Notation 解题报告(Python)

    [LeetCode]150. Evaluate Reverse Polish Notation 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/ ...

随机推荐

  1. hdu3685(几何重心与凸包结合)

    题意:给一个多边形(有可能是凹多边形).问有多少种可以使得它稳定放置的方式.当然稳定的原则就是重心做垂线在支撑点之内. 解法:由于有可能是凹多边形,所以先求出多边形的凸包,这是在放置时候会接触地面的全 ...

  2. OpenGL/GLSL数据传递小记(2.x)(转)

    本篇记录一下关于OpenGL程序中绑定各种GLSL变量的一些注意问题(有些是近期编写代码感受强烈的).以供参考.——ZwqXin.com 本文来源于 ZwqXin (http://www.zwqxin ...

  3. Problem A. Dynamic Grid

    Problem We have a grid with R rows and C columns in which every entry is either 0 or 1. We are going ...

  4. Dockerfile安装KOD可道云

    [root@docker01 base2]# cat Dockerfile FROM centos:6.8 RUN yum install openssh-server -y RUN /etc/ini ...

  5. StarUML破解教程

    StarUML破解教程 StarUML官方下载地址:http://staruml.io/download StarUML是一个非常好用的画UML图的工具,但是它是收费软件,以下是破解方法: 1.使用E ...

  6. windowsphone8.1学习笔记之应用数据(四)

    应用数据的存储格式常用的分为json和xml两种(其实我都想略过这个地方的,json我一直用的是json.net,而wp上操作xml的方式与其他相比也没太多变化). 先说说json数据存储,关于jso ...

  7. Apache转发规则的一点注意

    RewriteRule ^studio/$ book.php?mod=studio 这种目录转发, 正常情况下是没问题的. 但是当根目录下存在一个 studio 目录时, apache就不会转发URL ...

  8. 洛谷 1641 [SCOI2010]生成字符串

    题目戳这里 一句话题意 求\(C_{m+n}^{m}\)-\(C_{m+n}^{m-1}\) Solution 巨说这个题目很水 标签居然还有字符串? 但是我还不很会用逆元真的太菜了,还好此题模数P为 ...

  9. scikit-learn(project中用的相对较多的模型介绍):1.14. Semi-Supervised

    參考:http://scikit-learn.org/stable/modules/label_propagation.html The semi-supervised estimators insk ...

  10. importlib 模块导入

    #1.动态导入模块 script_name = scripts.utils module = importlib.import_module(script_name) # 动态导入相应模块 #2.模块 ...