类似这样的后缀表达式: 叫做逆波兰表达式["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (5 / 13)) -> 4 编译器比较喜欢从栈(stack)里面 pop 两个对象出来计算 然后 继续push 回去, 然后继续这样子计算下去..算法也很简单
public static void main(String[] args) { System.out.println(calRPN("4", "13", "5", "/", "+")); } public static int calRPN(String... tokens) { int ret = 0; String operators = "+-*/"; Stack<String> stack = new Stack<String>(); for (String t : tokens) { if (!operators.contains(t)) { stack.push(t); }else { int a = Integer.valueOf(stack.pop()); int b = Integer.valueOf(stack.pop()); int v = 0; if (t.equals("+")) { v = a + b; }else if (t.equals("-")) { v = a - b; }else if (t.equals("*")) { v = a * b; }else if (t.equals("/")) { v = a / b; } stack.push(String.valueOf(v)); } } ret = Integer.valueOf(stack.pop()); return ret; }
时间: 2024-10-16 00:33:10