zoukankan      html  css  js  c++  java
  • Evaluate Reverse Polish Notation

    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





    这道题还是比较Easy,直接用堆栈,遇到数字就进栈,遇到运算符弹出两个数,将运算结果入栈。最后返回栈底元素就okay了
    public class Solution {
        public int evalRPN(String[] tokens) {
            int top = -1;//栈指针
            int stack[] = new int[tokens.length / 2 + 1];
            
            for(int i = 0; i < tokens.length; i++){
                char temp = tokens[i].charAt(0);
                if(temp != '+' && !(tokens[i].length() == 1 && temp == '-')
                        && temp != '*' && temp != '/'){//数字直接入栈
                    stack[++top] = Integer.valueOf(tokens[i]);
                }
                else{//元素符,弹两个数字出来计算
                    int num1;
                    int num2;
                    int result = 0;
                    
                    num2 = stack[top--];
                    num1 = stack[top--];
                    switch(temp){
                        case '+':
                            result = num1 + num2;
                            break;//入栈
                        case '-':
                            result = num1 - num2;
                            break;
                        case '*':
                            result = num1 * num2;
                            break;
                        case '/':
                            result = num1 / num2;
                            break;
                    }
                    stack[++top] = result;//结果入栈
                    
                }
            }
            return stack[top];
        }
    }
     
  • 相关阅读:
    螺旋折线——第九届蓝桥杯C语言B组(省赛)第七题
    组合问题
    八皇后
    01背包(详解)
    最长递增子序列
    棋盘游戏
    The Accomodation of Students
    P3157 [CQOI2011]动态逆序对
    Building a Space Station
    焚风现象(差分模板题)
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4111291.html
Copyright © 2011-2022 走看看