Sponsored
Sponsored
This approach involves using a stack (or list) to simulate the score record. Each operation determines how you transform the record:
After processing all operations, sum up the stack to get the total score.
Time Complexity: O(n), where n is the number of operations.
Space Complexity: O(n), for the storage of scores in the stack.
1import java.util.Stack;
2
3public class BaseballGame {
4 public int calPoints(String[] ops) {
5 Stack<Integer> stack = new Stack<>();
6 for (String op : ops) {
7 if (op.equals("+")) {
8 int top = stack.pop();
9 int newTop = top + stack.peek();
10 stack.push(top);
11 stack.push(newTop);
12 } else if (op.equals("D")) {
13 stack.push(2 * stack.peek());
14 } else if (op.equals("C")) {
15 stack.pop();
16 } else {
17 stack.push(Integer.parseInt(op));
18 }
19 }
20 int sum = 0;
21 for (int score : stack) {
22 sum += score;
23 }
24 return sum;
25 }
26}
Utilizes the Stack class in Java to handle operations as per rules given. The stack is iterated for the final score calculation using a sum variable.
This approach leverages in-place list manipulation without using any explicit stack. Use a low-level list operation to track the scores and operations similar to calcualtions within the same list. Ideal for scripting languages that optimize list operations.
Time Complexity: O(n).
Space Complexity: O(n) due to maintaining result list as stack.
1def calPoints(ops):
2 record = []
3 for op in ops
Instead of a designated stack, the list itself is used to apply operations which may concatenate new scores or remove past ones. The final sum is the sum of list elements.