Leetcode Note: Go - Baseball Game

Baseball Game - LeetCode
https://leetcode.com/problems/baseball-game/

  • Go 言語で取り組んだメモ

所感

  • string 配列 ops が渡されるので、文字に応じてスコアを計算して int で return する

回答

Baseball Game - LeetCode
https://leetcode.com/problems/baseball-game/solution/

Golang solution in 3ms - LeetCode Discuss
https://leetcode.com/problems/baseball-game/discuss/107886/Golang-solution-in-3ms

func calPoints(ops []string) int {
    stack := make([]int, len(ops))
    top := 0

    for i := 0; i < len(ops); i++ {
        op := ops[i]
        switch op {
        case "+":
            last1 := stack[top-1]
            last2 := stack[top-2]
            stack[top] = last1 + last2
            top += 1
        case "D":
            last1 := stack[top-1]
            stack[top] = last1 * 2
            top += 1
        case "C":
            top -= 1
        default:
            stack[top], _ = strconv.Atoi(op)
            top += 1
        }
    }

    points := 0
    for i := 0; i < top; i++ {
        points += stack[i]
    }
    return points
}
  • stack を作って文字ごとに操作を行う
  • ループ終了後に最終的な集計を行い return