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.
1function calPoints(ops) {
2 let stack = [];
3 for (let op of ops) {
4 if (op === '+') {
5 stack.push(stack[stack.length - 1] + stack[stack.length - 2]);
6 } else if (op === 'D') {
7 stack.push(2 * stack[stack.length - 1]);
8 } else if (op === 'C') {
9 stack.pop();
10 } else {
11 stack.push(parseInt(op));
12 }
13 }
14 return stack.reduce((a, b) => a + b, 0);
15}
The logic uses an array as a stack to keep track of scores. According to the operation, scores are added, doubled, or removed. The final result is the sum of 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.