zoukankan      html  css  js  c++  java
  • 【后缀表达式求解】No.3.栈-evaluate-reverse-polish-notation题解(Java版)

    牛客网的题目链接

    题目描述

    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
    

    注意点

    可能存在输入值为负数的情况!其余的就按照后缀表达式来计算就OK了!
    开两个栈,数字栈满2和字符串栈不为空就进行一次运算,运算出结果后还放回数字栈!
    就酱~~
    Java语法写蒜法有点头疼,很多数值转换不如C/C++来的方便,多写写习惯了可能就好了.

    题解,仅供参考

    import java.util.Stack;
    public class Solution {
        public int evalRPN(String[] tokens) {
            int ans=0;
            //操作符栈
            Stack<String> op = new Stack<>();
            //数字栈
            Stack<String> num = new Stack<>();
            String opList = "+-*/";
    
            for(int i=0;i<tokens.length;i++){
                char ch = tokens[i].charAt(0);
    
                if(tokens[i].length()==1&&opList.indexOf(tokens[i].charAt(0))!=-1){
                    op.push(tokens[i]);
                }
                else{
                    num.push(tokens[i]);
                }
    
    
                //当数字>=2 并且 op栈>=1 时进行计算
                while(op.size()>=1&&num.size()>=2){
                    Integer integer1 = new Integer(num.pop());
                    Integer integer2 = new Integer(num.pop());
    
                    int index = opList.indexOf(op.pop());
                    switch (index){
                        case 0:
                            num.push( String.valueOf(integer1+integer2));
                            break;
                        case 1:
                            num.push( String.valueOf(integer2-integer1));
                            break;
                        case 2:
                            num.push( String.valueOf(integer1*integer2));
                            break;
                        case 3:
                            num.push( String.valueOf(integer2/integer1));
                            break;
                        default:
                            break;
                    }
                }
            }
            ans = Integer.valueOf(num.pop());
            return ans;
        }
    }
    
  • 相关阅读:
    Linux Shell入门
    Linux系统结构
    Ubuntu bond 配置
    VXLAN概述
    lsof
    入驻博客园,希望可以跟大家一起讨论,一起学习和进步。
    版本管理工具小乌龟TortoiseGit的安装和使用(2)
    版本管理工具小乌龟TortoiseGit的安装和使用(1)
    定义变量时未初始化赋值的问题
    BlackBerry 9900刷机
  • 原文地址:https://www.cnblogs.com/zhazhaacmer/p/11052736.html
Copyright © 2011-2022 走看看