Evaluate the value of an arithmetic exPRession in Reverse Polish Notation.Valid Operators are +, -, *, /. Each operand may be an integer or another expression.Some examples: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
難度:70. RPN中文名字叫做逆波蘭表示法,它的好處維基百科說了,就是不需要括號(hào)來表示運(yùn)算的先后,直接根據(jù)式子本身就可以求解。解題思路就是維護(hù)一個(gè)棧,遇到數(shù)字就入棧,遇到操作符就兩次出棧得到棧頂?shù)膬蓚€(gè)操作數(shù),運(yùn)用操作符進(jìn)行運(yùn)算以后,再把結(jié)果入棧。直到式子結(jié)束,此時(shí)棧中唯一一個(gè)元素便是結(jié)果。
以上代碼中有一個(gè)沒有周全的地方是沒有對(duì)逆波蘭式錯(cuò)誤的情況進(jìn)行出錯(cuò)處理,其實(shí)也不難,就是每次pop操作檢查??涨闆r,如果???,則說明出錯(cuò),throw an exception。還有就是最后檢查一下棧的size,如果不是1也說明運(yùn)算數(shù)多了,返回錯(cuò)誤。
 1 public class Solution { 2     public int evalRPN(String[] tokens) { 3         if (tokens==null || tokens.length==0) return 0; 4         LinkedList<Integer> stack = new LinkedList<Integer>(); 5         for (int i=0; i<tokens.length; i++) { 6             if (tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")) { 7                 if (stack.isEmpty()) return 0; 8                 int operand1 = stack.pop(); 9                 if (stack.isEmpty()) return 0;10                 int operand2 = stack.pop();11                 if (tokens[i].equals("+")) stack.push(operand2 + operand1);12                 if (tokens[i].equals("-")) stack.push(operand2 - operand1);13                 if (tokens[i].equals("*")) stack.push(operand2 * operand1);14                 if (tokens[i].equals("/")) stack.push(operand2 / operand1);15             }16             else {17                 stack.push(Integer.parseInt(tokens[i]));18             }19         }20         return stack.peek();21     }22 }新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注