682. Baseball Game
Вы ведете учет очков в бейсбольной игре с необычными правилами. В начале игры у вас пустая запись.
Вам дается список строк operations, где operations[i] — это i-я операция, которую вы должны применить к записи, и она может быть одной из следующих:
entier x.
Записать новый счет, равный x.
'+'.
Записать новый счет, который является суммой двух предыдущих очков.
'D'.
Записать новый счет, который в два раза больше предыдущего очка.
'C'.
Аннулировать предыдущее очко, удалив его из записи.
return сумму всех очков в записи после Applications всех операций.
Тестовые случаи сформированы таким образом, что ответ и все промежуточные вычисления умещаются в 32-битное entier, и что все операции корректны.
Exemple:
Input: ops = ["5","2","C","D","+"]
Output: 30
Explanation:
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.
C# solution
correspondant/originalpublic class Solution {
public int CalPoints(string[] ops) {
Stack<int> stack = new Stack<int>();
foreach (string op in ops) {
if (op == "+") {
int top = stack.Pop();
int newTop = top + stack.Peek();
stack.Push(top);
stack.Push(newTop);
} else if (op == "C") {
stack.Pop();
} else if (op == "D") {
stack.Push(2 * stack.Peek());
} else {
stack.Push(int.Parse(op));
}
}
int ans = 0;
foreach (int score in stack) {
ans += score;
}
return ans;
}
}
C++ solution
brouillon automatique, à relire avant soumission#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int CalPoints(vector<string> ops) {
stack<int> stack = new stack<int>();
foreach (string op in ops) {
if (op == "+") {
int top = stack.pop();
int newTop = top + stack.Peek();
stack.push(top);
stack.push(newTop);
} else if (op == "C") {
stack.pop();
} else if (op == "D") {
stack.push(2 * stack.Peek());
} else {
stack.push(int.Parse(op));
}
}
int ans = 0;
foreach (int score in stack) {
ans += score;
}
return ans;
}
}
Java solution
correspondant/originalclass Solution {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
for (String op : ops) {
if (op.equals("+")) {
int top = stack.pop();
int newTop = top + stack.peek();
stack.push(top);
stack.push(newTop);
} else if (op.equals("C")) {
stack.pop();
} else if (op.equals("D")) {
stack.push(2 * stack.peek());
} else {
stack.push(Integer.valueOf(op));
}
}
int ans = 0;
for (int score : stack) {
ans += score;
}
return ans;
}
}
Python solution
correspondant/originalclass Solution:
def calPoints(self, ops: List[str]) -> int:
stack = []
for op in ops:
if op == "+":
stack.append(stack[-1] + stack[-2])
elif op == "C":
stack.pop()
elif op == "D":
stack.append(2 * stack[-1])
else:
stack.append(int(op))
return sum(stack)
Algorithm
Поддерживайте значение каждого действительного раунда в стеке при обработке данных. Используйте стек, так как операции касаются только последнего или предпоследнего действительного раунда.
Обрабатывайте каждую операцию из списка operations последовательно, выполняя соответствующее действие: добавление, суммирование, удвоение или удаление очков.
После обработки всех операций return сумму всех значений в стеке.
😎
Vacancies for this task
offres actives with overlapping task tags are affichés.