Leetcode 682: Baseball Game

问题描述:
ou are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds’ scores.

At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:

An integer x - Record a new score of x.
“+” - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
“D” - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
“C” - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.
Return the sum of all the scores on the record.

棒球计分板:给定一个字符串类型的数组,如果字符串代表数字,则记录该分数;如果字符串为“+”,则记录前两个数字之和;若为“D”,则记录上一个数字的*2;若为“C”, 则抹去上一个记录。

思路:
形式新颖但思路很传统,就是逐一解析每一个位置,然后对应一个数组操作。

代码如下:

class Solution {
    public int calPoints(String[] ops) {
        List<Integer> myList = new ArrayList<>();
        int listPointer = 0;
        int sum = 0;
        for (int i=0; i<ops.length; i++){
            String thisSymbol = ops[i];
            if((!thisSymbol.equals("+"))&&(!thisSymbol.equals("D"))&&(!thisSymbol.equals("C"))){
                myList.add(Integer.parseInt(thisSymbol));
                listPointer++;
            }
            else if (thisSymbol.equals("+")){
                myList.add(myList.get(listPointer-2)+myList.get(listPointer-1));
                listPointer++;
            }
            else if(thisSymbol.equals("D")){
                myList.add(myList.get(listPointer-1)*2);
                listPointer++;
            }
            else{
                myList.remove(--listPointer);
            }
        }
        for(int i=0; i<myList.size(); i++){
            sum = sum+myList.get(i);
        }
        return sum;
    }
}

老生常谈,加深印象:如果需要数组但未知数组大小,各异借助arraylist然后转换成数组

时间复杂度: O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值