Evaluate Reverse Polish Notation

逆波兰表达式,不需要括号的表达式。好像就是从前数据结构书上学过的中缀表达式。
wikipedia上很好地解释了运算步骤,就是用stack。遇到符号就pop,结果push回去。
https://en.wikipedia.org/wiki/Reverse_Polish_notation
唯一要注意的是减号、除号的pop出栈的顺序。

   public int evalRPN(String[] tokens) {
       Stack<Integer> stack = new Stack<>();
       for (int i = 0; i < tokens.length; i++) {
           if (tokens[i].equals("+")) {
               stack.push(stack.pop() + stack.pop());
           } else if (tokens[i].equals("-")) {
               stack.push(-stack.pop() + stack.pop());
           } else if (tokens[i].equals("*")) {
               stack.push(stack.pop() * stack.pop());
           } else if (tokens[i].equals("/")) {
               int num1 = stack.pop();
               int num2 = stack.pop();
               stack.push(num2 / num1);
           } else {
               stack.push(Integer.parseInt(tokens[i]));
           }
       }
       return stack.peek();
   }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容