The title

You are the recorder of a special baseball game. This match is made up of a number of rounds, and points scored in past rounds may affect points scored in future rounds.

At the start of the game, the record was blank. You get a list of strings to record operations ops, where OPS [I] is the ith operation you need to record. Ops follows the following rules:

  1. The integer x – represents a new score x for the turn
  2. “+” – indicates that the new score for the turn is the sum of the previous two scores.
  3. “D” – Indicates that the new score scored in this turn is twice the previous score.
  4. “C” – indicates that the previous score is invalid and removed from the record.

Return the sum of all the scores in the record.

Source: LeetCode leetcode-cn.com/problems/ba…

Their thinking

Select the characters in the array according to the rules given in the question, and perform different stack operations on each of the four rules:

  1. Numbers are pushed into the stack
  2. “+” takes the top element + the second element and adds the result to the stack
  3. At “D”, take the top element * 2 and push the product onto the stack
  4. “C” indicates that the last result is invalid and the stack is removed

Finally add stack array return can be.

Code implementation

var calPoints = function(ops) {
    const stack = []
    ops.forEach(item => {
        if (isNaN(Number(item))) {
            if (item === 'C') {
                stack.pop()
            } else if (item === 'D') {
                stack.push(stack[stack.length -1]*2)
            } else if (item === '+') {
                stack.push(stack[stack.length - 1] + stack[stack.length - 2])
            }
        } else {
            stack.push(Number(item))
        }
    })

    return stack.reduce((prev, curr) => prev + curr)
};
Copy the code

If there are mistakes welcome to point out, welcome to discuss together!