Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 951 Bytes

682.棒球比赛.md

File metadata and controls

45 lines (39 loc) · 951 Bytes

682.棒球比赛

/*
 * @lc app=leetcode.cn id=682 lang=typescript
 *
 * [682] 棒球比赛
 */

// @lc code=start
function calPoints(ops: string[]): number {}
// @lc code=end

解法 1: 模拟

function calPoints(ops: string[]): number {
  const stack: number[] = []
  for (let op of ops) {
    if (op === '+') {
      stack.push(stack[stack.length - 1] + stack[stack.length - 2])
    } else if (op === 'D') {
      stack.push(stack[stack.length - 1] * 2)
    } else if (op === 'C') {
      stack.pop()
    } else {
      stack.push(Number(op))
    }
  }
  return stack.reduce((sum, num) => sum + num, 0)
}

Case

test.each([
  { input: { ops: ['5', '2', 'C', 'D', '+'] }, output: 30 },
  { input: { ops: ['5', '-2', '4', 'C', 'D', '9', '+', '+'] }, output: 27 },
  { input: { ops: ['1'] }, output: 1 },
])('input: ops = $input.ops', ({ input: { ops }, output }) => {
  expect(calPoints(ops)).toEqual(output)
})