OA原题描述参考:

注意:具体抽到的题目可能会有细微变化。

Given a string array representing a throw ball blocks, each string is either a number,

+, Z, X. Calculate total. If number, just add to total. If +, add last 2 scores to total.

If Z, remove last score from total. If X, double last score and add to toal.

Use 0 for any missing last score. 有些 corner cases 要考虑。

打棒球得分,给了一个String[] input,求最终score

如果是 integer, 就加给score(有负值)

如果是“x”, 将上一个值double ,加给score; 若没有上一个值,上一个值按0 计算

如果是“z”, 上一个成绩作废, score 剪掉上一值

如果是“+”,将上两个值相加,然后加给score

解题思路参考:

考察stack的使用和边界条件的处理。坑:+号的处理,处理Z和X要先看是否是空集。

参考答案:

    public static void main(String[] args) {
        SolutionAZBall azball = new SolutionAZBall();
        String[] score = {"5", "-2", "4", "Z", "X", "9", "+", "+"};
        System.out.println(azball.ballCount(score));
    }

    public int ballCount(String[] score) {
        if (score == null || score.length == 0) {
            return 0;
        }

        Stack<Integer> stack = new Stack<Integer>();

        int sum = 0;
        for (int i = 0; i < score.length; i++) {
            String block = score[i];
            System.out.println(block);
            int val = 0;
            if (!stack.isEmpty() && block.equals("Z")) {
                val = stack.pop();
                sum -= val;
            } else if (!stack.isEmpty() && block.equals("X")) {
                val = stack.peek() * 2;
                sum += val;
                stack.push(val);
            } else if (block.equals("+")) {
                int size = stack.size();
                if (size >= 2) {
                    val = stack.get(size - 1) + stack.get(size - 2);
                } else if (size == 1) {//?????
                    val = stack.get(size - 1);
                }
                sum += val;
                stack.push(val);
            } else {
                val = Integer.parseInt(block);
                sum += val;
                stack.push(val);
            }
            System.out.println("sum: " + sum + stack);
        }
        System.out.println(sum);
        return sum;
    }
}

results matching ""

    No results matching ""