2023-01-08|閱讀時間 ‧ 約 3 分鐘

LeetCode - Rings and Rods #2103 Easy

刷題筆記 Easy
題目說明:總共有 10 根竿子,3 種顏色,給予一 string 名為 rings,Ex: R0G1B2
意思是 第1根( index = 0 )有一個戒子,第2根( index = 1)有一個戒子,第3根(index = 2)有一個戒子
目標:回傳有幾根竿子同時有三個顏色的戒子
限制:
  • rings.length == 2 * n
  • 1 = n = 100
  • rings[i] where i is even is either 'R', 'G', or 'B' (0-indexed).
  • rings[i] where i is odd is a digit from '0' to '9' (0-indexed).
  1. 新增一個 array 總共 10 位,因為題目有限制竿子最多 10支
  2. array 裡面每一個位子0都預設 0,用於之後目標竿子戒子就 +1
  3. 因為 rings 裡面有可能會重複, ex: R0G1R0 所以要濾掉重複的,採用 new Set()
  4. 要將 rings 這個文字拆分成 R0 G1 B2 這樣的 array,採用 split
  5. 而 split 的內容則是 regex /(?=[RGB])/
  6. 用 reduce 跌代每個不重複的( 用 set 濾掉了)顏色戒子 ex : [R1,G2,B8]
 const countPoints = function(rings) {
  const arr = Array(10).fill(0)
  
  return [...new Set(rings.split(/(?=[RGB])/))].reduce((count, [, rod]) =>{
    if(arr[rod] == 2) count++  
    // 如果 arr[rod] 第rod根竿子已經是2了,而再度造訪代表現在就是第3個,也就是說湊滿一根竿子3種顏色的條件,所以直接 count++
    else arr[rod]++
    return count
  }, 0)
}

分享至
成為作者繼續創作的動力吧!
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.