Baseball game score
Standard · Write code · about 10 min
You keep score for a game with odd rules. Each string in ops is one of:
- an integer: a new score;
"+": a new score equal to the sum of the previous two valid scores;"D": a new score equal to double the previous valid score;"C": the previous valid score is cancelled and removed.
Return the sum of all valid scores after the last operation.
Example 1
Input:
[["5","2","C","D","+"]]
Output:
30
C removes 2, D adds 10, + adds 5 + 10 = 15. The total is 30.
Example 2
Input:
[["5","-2","4","C","D","9","+","+"]]
Output:
27
Constraints
- 1 ≤ ops.length ≤ 1, 000
- Integers are between -30, 000 and 30, 000
- "+" always has two previous valid scores; "C" and "D" have one
Learn the idea first: Stacks: push, pop, peek; array and linked implementations, a visual lesson.
More Stacks: push, pop, peek; array and linked implementations problems
- Overflow handling Warm-up
- State after a sequence Warm-up
- Implement a stack on an array Standard
- Spot the bug: pop returns the wrong value Standard
- Implement a stack with a linked list Challenge