[LeetCode系列]Evaluate Reverse Polish Notation

Evaluate 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



思考:观察例子,可以发现,操作符的处理优先级是根据数组的前后顺序作为优先级进行处理,所以没有必要对操作符进行入栈操作。
而对当前的操作符进行计算时,会取栈顶位置的头两个数进行运算,运算完将结果压入栈,此题不难理解,直接上代码:


代码:
 1 public class Solution {
 2     public int evalRPN(String[] tokens) {
 3         Stack<Integer> stack = new Stack<Integer>();
 4         String operators = "+-*/";
 5         for (String s:tokens) {
 6             if (!operators.contains(s)) {
 7                 int num = Integer.valueOf(s);
 8                 stack.push(num);
 9             } else {
10                 int a = 0; 
11                 int b = 0;
12                 if (!stack.isEmpty()) {
13                      a = Integer.valueOf(stack.pop());
14                 }
15                 if (!stack.isEmpty()) {
16                      b = Integer.valueOf(stack.pop());
17                 }
18                 int index = operators.indexOf(s);
19                 int c = 0;
20                 switch (index) {
21                     case 0:
22                            c = a + b;
23                            stack.push(c);
24                            break;
25                     case 1:
26                            c = b - a;
27                            stack.push(c);
28                            break;
29                     case 2:
30                            c = a * b;
31                            stack.push(c);
32                            break;
33                     case 3:
34                            c = b / a;
35                            stack.push(c);
36                            break;
37                 }
38             }
39         }
40         int value = stack.pop();
41         return value;
42     }
43 }

 

posted on 2014-04-10 16:56  Jam_01  阅读(146)  评论(0编辑  收藏  举报

导航