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. hector_localization hector_salm rplidar同时编译

    1.将hector_localization包clone到src文件夹  进行功能包依赖安装 cd test_ws rosdep update rosdep install --from-paths ...

  2. ACM算法整理(不断补充ing)

    动态规划 1.背包问题 (1)01背包 ,n) DFR(v,V,C[i]) F[v]=max(F[v],F[v-C[i]]+W[i]); } //初始化时 //若背包不一定装满F全初始化为0 //若装 ...

  3. 在freemarker文件中,html标签获取后台的值

    1.<#assign a='3333' /> 2.<input type="text" id="name" name="name&q ...

  4. watch 命令

    watch是一个非常实用的命令,基本所有的Linux发行版都带有这个小工具,如同名字一样,watch可以帮你监测一个命令的运行结果,省得你一遍遍的手动运行.在Linux下,watch是周期性的执行下个 ...

  5. FreeSWITCH版本更新

    [1]FreeSWITCH版本更新 从2014年10月底开始,FreeSWITCH代码库改为由stash管理,该管理工具能更好地与jira集成. 如果你以前已经clone了代码,请做如下更新: git ...

  6. Hp服务器 iLO3 使用方法

    首先iLO3 和ipmi什么关系?如下是我摘自:hp官网  的一段话 With HP iLO3, you can: Experience a fast Remote Console incorpora ...

  7. 不依任何赖第三方,单纯用vue实现Tree 树形控件

    这几天接到一个需求,里面有需要做一个属性组件,找的第三方的,但是不能完全满足我的需求,有这时间,我就自己做个小轮子吧. 先看效果图(红点之前用的字体图标,是个对号,这里为了方便,用圆圈代替了选中状态, ...

  8. iOS tableView自定义删除按钮

    // 自定义左滑显示编辑按钮 - (NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActio ...

  9. 【BZOJ4804】欧拉心算 莫比乌斯反演+线性筛

    [BZOJ4804]欧拉心算 Description 给出一个数字N Input 第一行为一个正整数T,表示数据组数. 接下来T行为询问,每行包含一个正整数N. T<=5000,N<=10 ...

  10. Channel (Java NIO)

    [正文]netty源码死磕1.3:  Java NIO Channel 1. Java NIO Channel 1.1. Java NIO Channel的特点 和老的OIO相比,通道和NIO流(非阻 ...