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/

posted on 2014-11-26 20:38  Yu's Garden  阅读(431)  评论(0编辑  收藏  举报

导航