首页 > 代码库 > [Leetcode][JAVA] Evaluate Reverse Polish Notation

[Leetcode][JAVA] Evaluate Reverse Polish Notation

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


使用栈即可实现。遇到运算符号即pop出俩数运算,否则push
由于测试用例没有非法的表达式,所以很容易即可ACCEPT

 1 public int evalRPN(String[] tokens) { 2         Stack<String> st = new Stack<String>(); 3         for(int i=0;i<tokens.length;i++) 4         { 5             String t = tokens[i]; 6             if(t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")) 7             { 8                 int x2 = Integer.parseInt(st.pop()); 9                 int x1 = Integer.parseInt(st.pop());10                 if (t.equals("+"))11                     st.push(String.valueOf(x1 + x2));12                 else if (t.equals("-"))13                     st.push(String.valueOf(x1 - x2));14                 else if (t.equals("*"))15                     st.push(String.valueOf(x1 * x2));16                 else17                     st.push(String.valueOf(x1 / x2));18             }19             else20                  st.push(t);21         }22         23         return Integer.parseInt(st.pop());24     }

 



[Leetcode][JAVA] Evaluate Reverse Polish Notation