标签:style blog http color io 使用 java ar strong
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 else 17 st.push(String.valueOf(x1 / x2)); 18 } 19 else 20 st.push(t); 21 } 22 23 return Integer.parseInt(st.pop()); 24 }
[Leetcode][JAVA] Evaluate Reverse Polish Notation
标签:style blog http color io 使用 java ar strong
原文地址:http://www.cnblogs.com/splash/p/3963665.html