Leetcode / 682. Baseball Game
Pick a programming language:
Here is the source code for the solution to this problem.
import java.util.Stack;
class Solution {
public int calPoints(String[] operations) {
Stack<String> stack = new Stack<String>();
for (int i = 0; i < operations.length; i++) {
if (operations[i].equals("D")) {
int peeked = Integer.parseInt(stack.peek());
stack.push(Integer.toString(peeked * 2));
}
else if (operations[i].equals("C")) {
stack.pop();
}
else if (operations[i].equals("+")) {
String popped = stack.pop();
int operand1 = Integer.parseInt(popped);
int operand2 = Integer.parseInt(stack.peek());
stack.push(popped);
stack.push(Integer.toString(operand1 + operand2));
}
else {
// an integer
stack.push(operations[i]);
}
}
int sum = 0;
while (!stack.isEmpty()) {
sum += Integer.parseInt(stack.pop());
}
return sum;
}
}
Did you like the lesson? 😆👍
Consider a donation to support our work: