zoukankan      html  css  js  c++  java
  • Java for LeetCode 150 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
    解题思路:

    计算逆波兰表达式,Stack的经典应用,JAVA实现如下:

    	public int evalRPN(String[] tokens) {
    		if (tokens == null || tokens.length == 0)
    			return 0;
    		Stack<Integer> stack = new Stack<Integer>();
    		for (String str : tokens) {
    			if (str.length() > 1 || Character.isDigit(str.charAt(0)))
    				stack.push(Integer.parseInt(str));
    			else {
    				int a = stack.pop();
    				int b = stack.pop();
    				if (str.equals("+"))
    					stack.push(b + a);
    				else if (str.equals("-"))
    					stack.push(b - a);
    				else if (str.equals("*"))
    					stack.push(b * a);
    				else if (str.equals("/"))
    					stack.push(b / a);
    			}
    		}
    		return stack.pop();
    	}
    
  • 相关阅读:
    配置FTP服务
    Tomcat
    LNMP环境配置(下)
    LNMP环境配置(上)
    Ansible---
    Ansible
    正则三剑客-------grep
    Docker仓库的使用与维护
    Docker 引擎的安装 -->>存储库安装
    shell脚本实例
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4553866.html
Copyright © 2011-2022 走看看