zoukankan      html  css  js  c++  java
  • LeetCode——逆波兰表达式求值

    Q:计算逆波兰式(后缀表达式)的值
    运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
    例如:

    ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵ ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

    A:使用栈,碰到符号就跳出来两个值计算再压入结果

    import java.util.Stack;
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack();
            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();
                    if (tokens[i].equals("+"))
                        stack.push(a + b);
                    else if (tokens[i].equals("-"))
                        stack.push(b - a);
                    else if (tokens[i].equals("*"))
                        stack.push(a * b);
                    else if (tokens[i].equals("/"))
                        stack.push(b / a);
                }
            }
            return stack.pop();
        }
    
  • 相关阅读:
    python列表[]中括号
    python元组()小括号
    python break continue跳过和跳出循环
    python FOR循环
    python while循环
    python if elif else判断语句
    python使用变量
    python -input用户输入
    pycharm模板
    港股收费
  • 原文地址:https://www.cnblogs.com/xym4869/p/12426795.html
Copyright © 2011-2022 走看看