题目链接
法一
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new LinkedList();
for (String token : tokens) {
if (token.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (token.equals("-")) {
stack.push(-stack.pop() + stack.pop());
} else if (token.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (token.equals("/")) {
int b = stack.pop(), a = stack.pop();
stack.push(a / b);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
本地测试
lay.showTitle(150);
Solution150 sol150 = new Solution150();
String[] tokens150 = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
System.out.println(Arrays.toString(tokens150));
System.out.println(sol150.evalRPN(tokens150));