牛客网编程练习之编程马拉松:不喜欢括号
前缀表达式计算规则:
1. 从后往前读
2. 遇数字进栈,遇操作符栈顶两个出栈计算,结果再入栈。
这里假定前缀表达式是合法的,没有做合法性校验。
AC代码:
import java.util.Scanner; import java.util.Stack; /** * @author CC11001100 */ public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { sc.nextLine(); System.out.println(prefixComplete(sc.nextLine())); } } private static int prefixComplete(String expression) { Stack<Integer> stack = new Stack<>(); String[] ss = expression.split("\\s+"); for (int i = ss.length - 1; i >= 0; i--) { String s = ss[i]; switch (s) { case "+": stack.push(stack.pop() + stack.pop()); break; case "-": stack.push(stack.pop() - stack.pop()); break; case "*": stack.push(stack.pop() * stack.pop()); break; case "/": stack.push(stack.pop() / stack.pop()); break; default: stack.push(Integer.valueOf(s)); } } return stack.pop(); } }