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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int CalPoints(string[] ops) {
6 Stack<int> stack = new Stack<int>();
7 foreach (string op in ops) {
8 switch (op) {
9 case "+":
10 int top = stack.Pop();
11 int newTop = top + stack.Peek();
12 stack.Push(top);
13 stack.Push(newTop);
14 break;
15 case "D":
16 stack.Push(2 * stack.Peek());
17 break;
18 case "C":
19 stack.Pop();
20 break;
21 default:
22 stack.Push(Int32.Parse(op));
23 break;
24 }
25 }
26 int sum = 0;
27 foreach (int score in stack) {
28 sum += score;
29 }
30 return sum;
31 }
32}
A C# implementation using a Stack to simulate the record. The scores are manipulated based on type of operation encountered within a foreach loop over operations.
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.