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)