LeetCode 682. 棒球比赛题解

682. 棒球比赛题解

题目来源:682. 棒球比赛

2022.03.26 每日一题

LeetCode 题解持续更新中Github仓库地址 CSDN博客地址

今天的题目就很简单了,按照题意对整个操作进行模拟 ,就可以得到最终的结果

class Solution {
public:
    int calPoints(vector<string> &ops) {
        // 创建变量 n 统计当前分数的个数
        int n = 0;
        // 统计最后的得分情况
        int res = 0;
        // 创建一个数组,统计分数
        vector<int> list;
        // 遍历字符串数组
        for (string s: ops) {
            // 如果是 “+” 就取最后两个数组相加,并将对应的值加入数组
            if ("+" == s) {
                res += (list[n - 1] + list[n - 2]);
                list.push_back(list[n - 1] + list[n - 2]);
                // 更新 n
                n++;
                continue;
            }
            // 如果是 “D” 就取最后的结果*2,并将对应的值加入数组
            if ("D" == s) {
                res += 2 * list[n - 1];
                list.push_back(2 * list[n - 1]);
                // 更新 n 值
                n++;
                continue;
            }
            // // 如果是 “C” 就删除最后的结果,并将对应的值移除数组
            if ("C" == s) {
                res -= list[n - 1];
                list.pop_back();
                n--;
                continue;
            }
            // 将 字符串转成数字
            int t = stoi(s);
            // 添加到对应的值,并且更新相应的值
            res += t;
            n++;
            list.push_back(t);
        }
        // 返回结果
        return res;
    }
};
class Solution {
    public int calPoints(String[] ops) {
        // 创建变量 n 统计当前分数的个数
        int n = 0;
        // 统计最后的得分情况
        int res = 0;
        // 创建一个数组,统计分数
        ArrayList<Integer> list = new ArrayList<>();
        // 遍历字符串数组
        for (String s : ops) {
            // 如果是 “+” 就取最后两个数组相加,并将对应的值加入数组
            if ("+".equals(s)) {
                res += (list.get(n - 1) + list.get(n - 2));
                list.add(list.get(n - 1) + list.get(n - 2));
                // 更新 n
                n++;
                continue;
            }
            // 如果是 “D” 就取最后的结果*2,并将对应的值加入数组
            if ("D".equals(s)) {
                res += 2 * list.get(n - 1);
                list.add(2 * list.get(n - 1));
                // 更新 n 值
                n++;
                continue;
            }
            // // 如果是 “C” 就删除最后的结果,并将对应的值移除数组
            if ("C".equals(s)) {
                res -= list.get(n - 1);
                list.remove(n - 1);
                n--;
                continue;
            }
            // 将 字符串转成数字
            int t = Integer.parseInt(s);
            // 添加到对应的值,并且更新相应的值
            res += t;
            n++;
            list.add(t);
        }
        // 返回结果
        return res;
    }
}
  • 时间复杂度 O ( n ) O(n) O(n)
  • 空间复杂度 O ( n ) O(n) O(n)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值