zoukankan      html  css  js  c++  java
  • 【JAVA】【leetcode】【使用堆栈实现后向计算】

    题目: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

    理解:

    后向计算,如(2,1+3*),实为(2+1)*3;使用堆栈实现的原理就是push(2)进栈,push(1)进栈,当遇到符号“+”时,a = pop(),再b = pop(),实现b+a,

    然后将(b+a)的和再push进栈,等到下一个符号的到来时再pop出栈参与计算,直到计算完输入的所有字符。

    import java.util.*;
    public class Solution {
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<Integer>();
            for(int i=0;i<tokens.length;i++){
                try{
                    int num = Integer.parseInt(tokens[i]);
                    stack.push(num);
                }catch(Exception e){
                    int a = stack.pop();
                    int b = stack.pop();
                    stack.push(operate(b,a,tokens[i]));
                }
            }
            return stack.pop();
        }     
            public int operate(int a,int b,String token){
                switch(token){
                    case"+": return a+b;
                    case"-": return a-b;
                    case"*": return a*b;
                    case"/":
                    if(b==0)
                        return 0;
                    else
                        return a/b;
                    default:return 0;
                }
            }
            
    }



  • 相关阅读:
    CentOS 7 安装 MariaDB
    yum工具使用 -- 配置自定义yum源
    CentOS 7 安装 redis
    CentOS 7 安装Python3 + 虚拟环境 + django
    Linux 安装 Python3.6.5
    CentOS 7 安装Python3 虚拟环境
    oracle数据库分页原理
    POI工具类
    IoDH单例模式
    为什么使用单例模式【转】
  • 原文地址:https://www.cnblogs.com/weimiaomiao/p/5847145.html
Copyright © 2011-2022 走看看