LeetCode-Evaluate Reverse Polish Notation[AC源碼]

來源:互聯網
上載者:User

標籤:des   style   blog   color   io   for   ar   2014   

 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) -> 911  *             ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 612  * 13  * @Author LiuWei14  * @Date 2014年8月16日上午11:31:0515  * @Mail [email protected] 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 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.