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.
1def calPoints(ops):
2 stack = []
3 for op in ops:
4 if op == '+':
5 stack.append(stack[-1] + stack[-2])
6 elif op == 'D':
7 stack.append(2 * stack[-1])
8 elif op == 'C':
9 stack.pop()
10 else:
11 stack.append(int(op))
12 return sum(stack)
We used a list to implement a stack to record scores based on the operations. We iterate over each operation and update the stack accordingly. Finally, we return the sum of elements in the stack.
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.