682.棒球比赛
链接:682.棒球比赛
难度:Easy
标签:栈、数组、模拟
简介:请你返回记录中所有得分的总和。
题解 1 - python
- 编辑时间:2024-07-29
- 执行用时:32ms
- 内存消耗:16.43MB
- 编程语言:python
- 解法介绍:枚举每一个块与另一个块是否位置产生交集。
class Solution:
def calPoints(self, operations: List[str]) -> int:
s = []
for op in operations:
if op == '+':
s.append(s[-1] + s[-2])
elif op == 'D':
s.append(s[-1] * 2)
elif op == 'C':
s.pop()
else:
s.append(int(op))
return sum(s)
题解 2 - typescript
- 编辑时间:2021-03-19
- 执行用时:80ms
- 内存消耗:39.9MB
- 编程语言:typescript
- 解法介绍:dfs。
class Solution {
public:
int calPoints(vector<string> &ops) {
vector<int> list;
for (auto &op : ops) {
int n = list.size();
if (op == "+") {
list.push_back(list[n - 1] + list[n - 2]);
} else if (op == "D") {
list.push_back(list[n - 1] * 2);
} else if (op == "C") {
list.pop_back();
} else {
list.push_back(stoi(op));
}
}
int ans = 0;
for (auto &num : list) ans += num;
return ans;
}
};
题解 3 - cpp
- 编辑时间:2022-03-26
- 执行用时:4ms
- 内存消耗:8.1MB
- 编程语言:cpp
- 解法介绍:dfs。
class Solution {
public:
int calPoints(vector<string> &ops) {
vector<int> list;
for (auto &op : ops) {
int n = list.size();
if (op == "+") {
list.push_back(list[n - 1] + list[n - 2]);
} else if (op == "D") {
list.push_back(list[n - 1] * 2);
} else if (op == "C") {
list.pop_back();
} else {
list.push_back(stoi(op));
}
}
int ans = 0;
for (auto &num : list) ans += num;
return ans;
}
};