LeetCode-Evaluate Reverse Polish Notation[AC源码]

 1 package com.lw.leet2;
 2 
 3 /**
 4  * @ClassName:Solution
 5  * @Description:
 6  *         Evaluate the value of an arithmetic expression in Reverse Polish Notation.
 7  *         Valid operators are +, -, *, /. Each operand may be an integer or another expression.
 8  *     
 9  *         Some examples:
10  *             ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
11  *             ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
12  * 
13  * @Author LiuWei
14  * @Date 2014年8月16日上午11:31:05
15  * @Mail nashiyue1314@163.com 
16  */
17 public class Solution {
18     
19     private boolean isOper(String s){
20         if(s.equals("+")){
21             return true;
22         }
23         if(s.equals("-")){
24             return true;
25         }
26         if(s.equals("*")){
27             return true;
28         }
29         if(s.equals("/")){
30             return true;
31         }
32         return false;
33     }
34     
35     private String getOperRes(String num1,String num2,String oper){
36         if(oper.equals("+")){
37             return Integer.valueOf(num1)+Integer.valueOf(num2)+"";
38         }
39         else if(oper.equals("-")){
40             return Integer.valueOf(num1)-Integer.valueOf(num2)+"";
41         }
42         else if(oper.equals("*")){
43             return Integer.valueOf(num1)*Integer.valueOf(num2)+"";
44         }
45         else{
46             return Integer.valueOf(num1)/Integer.valueOf(num2)+"";
47         }
48     }
49     
50     public int evalRPN(String[] tokens) {
51         String[] resArr = new String[tokens.length];
52         int index =0;
53         for(int i=0;i<tokens.length;i++){
54             if(isOper(tokens[i])){
55                 String num1 = resArr[index-1];
56                 String num2 = resArr[index-2];
57                 resArr[index-2] = getOperRes(num2, num1, tokens[i]);
58                 index--;
59             }
60             else{
61                 resArr[index] = tokens[i];
62                 index ++;
63             }
64         }
65         return Integer.valueOf(resArr[0]);
66     }
67     
68     public static void main(String[] args){
69         Solution s = new Solution();
70 //        String [] tokens = {"4", "13", "5", "/", "+"};
71         String [] tokens = {"2", "1", "+"};
72         System.out.println(s.evalRPN(tokens));
73     }
74 }
原文地址:https://www.cnblogs.com/nashiyue/p/3916278.html