题解 | #逆波兰表达式求值#
逆波兰表达式求值
https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382
import java.util.*; public class Solution { private static final Deque<Integer> stack = new ArrayDeque<>(); public int evalRPN (String[] tokens) { // write code here for (int i = 0; i != tokens.length; ++i) { if (tokens[i].equals("+")) { stack.push(stack.pop() + stack.pop()); } else if (tokens[i].equals("-")) { int last = stack.pop(); stack.push(stack.pop() - last); } else if (tokens[i].equals("*")) { stack.push(stack.pop() * stack.pop()); } else if (tokens[i].equals("/")) { int last = stack.pop(); stack.push(stack.pop() / last); } else { stack.push(Integer.parseInt(tokens[i])); } } if (stack.isEmpty()) { return 0; } return stack.peek(); } }