1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| import static org.junit.Assert.assertSame;
public class EvaluateReversePolishNotation { public int evalRPN(String[] tokens) { if (tokens == null || tokens.length == 0) { return 0; } Stack<Integer> stack = new Stack<Integer>(); for (String s : tokens) { if (isOperator(s)) { if (stack.size() < 2) { return 0; } int b = stack.pop(); int a = stack.pop(); int result = getResult(a, b, s); stack.push(result); } else { int c = Integer.valueOf(s); stack.push(c); } } return stack.size() != 1 ? 0 : stack.pop(); } private boolean isOperator(String s) { if (s == null || s.length() > 1) { return false; } char c = s.charAt(0); return c == '+' || c == '-' || c == '*' || c == '/'; } private int getResult(int a, int b, String c) { char op = c.charAt(0); switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; default: return 0; } } @Test public void test() { String[] tokens = new String[]{"2", "1", "+", "3", "*"}; assertSame(9, evalRPN(tokens)); } }
|