for t in tokens: if t notin {"+", "-", "*", "/"}: stack.append(int(t)) else: right, left = stack.pop(), stack.pop() # print(left, t, right) if t == '+': stack.append(left + right) elif t == '-': stack.append(left - right) elif t == '*': stack.append(left * right) else: stack.append(trunc(left / right))
return stack[0]
用 Java 实现相同的算法。
classSolution{ publicintevalRPN(String[] tokens){ Deque<Integer> stack = new LinkedList<>(); for (String t : tokens) { if ("+".equals(t)) { stack.offerLast(stack.pollLast() + stack.pollLast()); } elseif ("-".equals(t)) { stack.offerLast(-stack.pollLast() + stack.pollLast()); } elseif ("*".equals(t)) { stack.offerLast(stack.pollLast() * stack.pollLast()); } elseif ("/".equals(t)) { Integer right = stack.pollLast(), left = stack.pollLast(); stack.offerLast(left / right); } else { stack.offerLast(Integer.valueOf(t)); } } return stack.peek(); } }