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.
1#include <vector>
2#include <string>
3#include <numeric>
4
5int calPoints(std::vector<std::string>& ops) {
6 std::vector<int> stack;
7 for (const auto& op : ops) {
8 if (op == "+") {
9 stack.push_back(stack.back() + stack[stack.size() - 2]);
10 } else if (op == "D") {
11 stack.push_back(2 * stack.back());
12 } else if (op == "C") {
13 stack.pop_back();
14 } else {
15 stack.push_back(std::stoi(op));
16 }
17 }
18 return std::accumulate(stack.begin(), stack.end(), 0);
19}
Use a vector to act as a stack. Each operation modifies the score vector as instructed by the rules. Finally, accumulate the values in the vector for the total score.
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.