150. Evaluate Reverse Polish Notation

The main idea is to use the stack to solve the problem. When it is judged to be an integer, it is pushed into the stack. When it is an operator, the first two numbers on the stack are popped and operated.

code show as below:

 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324890762&siteId=291194637