LeetCode: 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

SOLUTION 1:

以下摘自维基:

http://en.wikipedia.org/wiki/Reverse_Polish_notation

Example[edit]
The infix expression "5 + ((1 + 2) × 4) − 3" can be written down like this in RPN:

5 1 2 + 4 × + 3 −
The expression is evaluated left-to-right, with the inputs interpreted as shown in the following table (the Stack is the list of values the algorithm is "keeping track of" after the Operation given in the middle column has taken place):

从这里可以看出,我们使用一个Stack就可以完成计算,非常简单。只需要从左往右结合,每遇到一个运算符号,就将前面两个数字弹出并且计算,然后再push回去。

全部计算完成后,再将结果弹出即可。

 1 public class Solution {
 2     public int evalRPN(String[] tokens) {
 3         if (tokens == null) {
 4             return 0;
 5         }
 6         
 7         int len = tokens.length;
 8         Stack<Integer> s = new Stack<Integer>();
 9         
10         for (int i = 0; i < len; i++) {
11             String str = tokens[i];
12             if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")) {
13                 // get out the two operation number.
14                 int n2 = s.pop();
15                 int n1 = s.pop();
16                 if (str.equals("+")) {
17                     s.push(n1 + n2);
18                 } else if (str.equals("-")) {
19                     s.push(n1 - n2);
20                 } else if (str.equals("*")) {
21                     s.push(n1 * n2);
22                 } else if (str.equals("/")) {
23                     s.push(n1 / n2);
24                 }
25             } else {
26                 s.push(Integer.parseInt(str));
27             }
28         }
29         
30         if (s.isEmpty()) {
31             return 0;
32         }
33         
34         return s.pop();
35     }
36 }

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/stack/EvalRPN.java

 

参考答案:

http://www.ninechapter.com/solutions/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值