Leetcode 150. Evaluate Reverse Polish Notation

Similar Questions Basic Calculator Expression Add Operators

思路:逆波兰式的计算(Reverse Polish Notation),利用栈,正向遍历String数组,遇到符号字符,就将栈顶的2个元素弹出做对应计算,将计算结果压栈;遇到数字,直接压栈。

 1 class Solution {
 2     public int evalRPN(String[] tokens) {
 3         Stack<Integer> s = new Stack<Integer>();
 4         for(int i = 0; i < tokens.length; i++) {
 5             int a, b;
 6             switch(tokens[i]) {
 7                 case "+": 
 8                     s.push(s.pop() + s.pop());
 9                     break;
10                 case "-":
11                     a = s.pop();
12                     b = s.pop();
13                     s.push(b - a);
14                     break;
15                 case "*": 
16                     s.push(s.pop() * s.pop());
17                     break;
18                 case "/": 
19                     a = s.pop();
20                     b = s.pop();
21                     s.push(b / a);
22                 break;
23                 default: s.push(Integer.parseInt(tokens[i]));
24             }
25         }
26         return s.pop();
27     }
28 }

Next challenges: Expression Add Operators

posted @ 2018-02-19 20:55  Deribs4  阅读(233)  评论(0编辑  收藏  举报