栈计算问题

题意是给一组数字+符号(自增1:^,相乘*,相加+)和一个长度为16的stack。栈空取数返回-1,栈满推数返回-2。

输入样例是1 1 + 2 ^ 3 * 这样子,做的时候紧张忽略了空格,用char处理的,结果炸了,只过了40%,因为那时候只有3分钟了。结束后猛然发现。代码应该是这样的。

import java.util.Scanner;
import java.util.Stack;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String line = in.nextLine();
        if (line != null && !line.isEmpty()) {
            int res = resolve(line.trim());
            System.out.println(String.valueOf(res));
        }
    }

    // write your code here
    public static int resolve(String expr) {
        Stack<Integer> stack = new Stack<>();
        String[] patterns = expr.split(" ");
        for (String pattern : patterns) {
            if (pattern.equals("*")) {
                if (stack.size() < 2) return -1;
                stack.push(stack.pop() * stack.pop());
            } else if (pattern.equals("+")) {
                if (stack.size() < 2) return -1;
                stack.push(stack.pop() + stack.pop());
            } else if (pattern.equals("^")) {
                if (stack.isEmpty()) return -1;
                Integer integer = stack.pop();
                stack.push(++integer);
            } else {
                if (stack.size() >= 16) return -2;
                stack.push(Integer.parseInt(pattern));
            }
        }
        return stack.pop();
    }
}
原文地址:https://www.cnblogs.com/cielosun/p/6771275.html