150. Evaluate Reverse Polish Notation

主要思路是使用堆栈去解决问题,当判断是整数的时候入栈,当是运算符的时候,将堆栈前两个数字弹出并进行运算。

代码如下:

 1 class Solution {
 2     public int evalRPN(String[] tokens) {
 3         Stack<Integer> sck = new Stack<Integer>();
 4         int param1, param2, res = 0;
 5         
 6         if(tokens.length == 1){
 7             return Integer.parseInt(tokens[0]);
 8         }
 9         
10         String regex = "^-?\\d+$";
11         
12         for(int i = 0 ; i < tokens.length ; i++){
13             if(tokens[i].matches(regex)){
14                 sck.push(Integer.parseInt(tokens[i]));
15             }else{
16                 param2 = sck.pop();
17                 param1 = sck.pop();
18                 switch(tokens[i]){
19                     case "+": {
20                         res = param1 + param2;
21                         sck.push(res);
22                         break;
23                     }
24                     case "-": {
25                         res = param1 - param2;
26                         sck.push(res);
27                         break;
28                     }
29                     case "/": {
30                         res = param1/param2;
31                         sck.push(res);
32                         break;
33                     }
34                     case "*":{
35                         res = param1 * param2;
36                         sck.push(res);
37                         break;
38                     }
39                 }
40             }
41         }
42         
43         return res;
44     }
45 }

END

猜你喜欢

转载自www.cnblogs.com/sssysukww/p/8940133.html