码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Evaluate Reverse Polish Notation

时间:2015-08-12 12:59:19      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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

     看到这道题说实话很有亲切感啊哈哈。因为以前上课的时候有次作业就和这道题灰常灰常的像,当时才开始学不久,把我折腾的哈哈~

     刚开始我是按照以前的思考方式(因为懒)各种if statement啊各种special case啊。。写了一堆看着又恼火又长,然后还老不过。(抓狂的节奏-。-)

     后来索性打乱开始重新写,事实证明还是要勤于思考。

     果断直接用switch就轻松解决了。哈哈哈~~

     再废话一句,后面参考了有人post的答案做了进一步修改,在“-”的运算时,固有思维是要有一个临时int来辅助计算,但是其实我们可以把“-”转换成“+”。

     比如b-a=-a+b 这样我们就完全不需要临时的int了,不过除法还是需要的哈。

public class Solution {
  public int evalRPN(String[] tokens) {
  Stack<Integer> stack = new Stack<Integer>();

  for (int i = 0; i < tokens.length; i++) {
    switch (tokens[i]) {
      case "+":
        stack.push(stack.pop() + stack.pop());
        break;

      case "-":
        stack.push(-stack.pop() + stack.pop());
        break;

      case "/":
        int a = stack.pop(), b = stack.pop();
        stack.push(b/a);
        break;
        
      case "*":
        stack.push(stack.pop() * stack.pop());
        break;

      default:
        stack.push(Integer.parseInt(tokens[i]));
    }
  }

  return stack.pop();
}
}

 

[LeetCode] Evaluate Reverse Polish Notation

标签:

原文地址:http://www.cnblogs.com/orangeme404/p/4723776.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!