Baseball Game — Stack Simulation
Advertisement
Problem 255 · Baseball Game
Difficulty: Easy · Pattern: Stack Simulation
Solutions
# Python
def calPoints(ops):
stack = []
for op in ops:
if op == '+': stack.append(stack[-1] + stack[-2])
elif op == 'D': stack.append(2 * stack[-1])
elif op == 'C': stack.pop()
else: stack.append(int(op))
return sum(stack)
// Java
public int calPoints(String[] ops) {
Deque<Integer> stack = new ArrayDeque<>();
for (String op : ops) {
if (op.equals("+")) { int a = stack.pop(), b = stack.peek(); stack.push(a); stack.push(a+b); }
else if (op.equals("D")) stack.push(2 * stack.peek());
else if (op.equals("C")) stack.pop();
else stack.push(Integer.parseInt(op));
}
return stack.stream().mapToInt(Integer::intValue).sum();
}
Complexity
- Time: O(n)
- Space: O(n)
Advertisement