Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit series activities – click on the task to see the details of the activities.
682. The baseball game
Subject analysis
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 that record operations
ops
, includingops[i]
Are youThe ith operation that needs to be recorded
, OPS follows the followingThe rules
:Integer x
: indicates a new score x for the turn"+"
: indicates that the new score of the turn isThe sum of the first two scores
. The question data ensures that this operation is always preceded by two valid scores."D"
: indicates that the new score of the turn isTwice as many points as the previous one
. The question data ensures that this operation is always preceded by a valid score when recording it."C"
Said:The previous score is invalid and removed from the record
. The question data ensures that this operation is always preceded by a valid score when recording it.
Returns the sum of all scores in the record.
Thinking on
The content of each operation is the previous two or the previous content, so the stack operation is suitable.
- Start by creating a stack to keep track of scores
- And then iterate through the array
- encounter
digital
It into the stack - encounter
C
Will pop up the stack - encounter
D
willTop element *2
, and then multiplies onto the stack - encounter
+
Just add the last two elements, and then push them on the stack
- encounter
- When traversal is complete, return the sum of all scores
The sample
Input: ops = ["5"."2"."C"."D"."+"] output: 30"5"- Record + 5, record is now [5]"2"- Record + 2, record is now [5, 2]"C"- Invalidate the previous score and remove it, the record is now [5]."D"- Record plus 2 * 5 = 10, record is now [5, 10]."+"- Record + 5 + 10 = 15, record is now [5, 10, 15]. The sum of all points 5 + 10 + 15 = 30Copy the code
code
/* * @lc app=leetcode.cn id=682 lang=javascript * * [682] baseball game */
// @lc code=start
/ * * *@param {string[]} ops
* @return {number}* /
var calPoints = function(ops) {
let result = []
for (num of ops) {
switch (num) {
case 'C': // Pop the previous round score
result.pop()
break;
case 'D': // Double the score of the previous round
result.push(result[result.length - 1] * 2)
break;
case '+': // The scores of the last two rounds
result.push(result[result.length - 1] + result[result.length - 2])
break;
default:
result.push(Number(num))
break; }}return result.reduce((a, b) = > a + b)
};
// @lc code=end
Copy the code