Fork me on GitHub

牛客网编程练习之编程马拉松:不喜欢括号

image

image

 

前缀表达式计算规则:

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();
	}

}

 

题目来源: https://www.nowcoder.com/practice/82215ba86ace4a2690fd9ded27fe9f49?tpId=3&tqId=10883&tPage=1&rp=&ru=/ta/hackathon&qru=/ta/hackathon/question-ranking

posted @ 2017-12-14 00:35  CC11001100  阅读(319)  评论(0编辑  收藏  举报