LeetCode - Rings and Rods #2103 Easy

閱讀時間約 2 分鐘

刷題筆記 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)
}
0會員
1內容數
留言0
查看全部
發表第一個留言支持創作者!
你可能也想看
Leetcode 精選75題 分配比重 題目與題解 熱門考點 演算法框架複習 目錄 Leetcode 精選75題 題目與題解 熱門考點 目錄 (持續更新中) 建議從左側目錄 或者 按Ctrl+F輸入關鍵字進行搜尋
Thumbnail
avatar
小松鼠
2024-05-29
[LeetCode] 875 - Koko Eating Bananas[LeetCode] 875 - Koko Eating Bananas 解題
avatar
Tumi
2024-02-29
[Leetcode] 121. Best Time to Buy and Sell Stock題目 : 121. Best Time to Buy and Sell Stock
Thumbnail
avatar
Youna
2024-02-13
Leetcode 30 天 Pandas 挑戰分享參加Leetcode的30 Days of Pandas挑戰,除了是學習的機會,更是練習熟悉pandas功能的機會。文章分享了挑戰簡介、題目描述、關鍵技術以及參加挑戰的心得。適合新手學習pandas,也可提升熟練度。
Thumbnail
avatar
Karen
2024-01-30
[Leetcode] 100. Same Tree題目 : 100. Same Tree
Thumbnail
avatar
Youna
2024-01-11
【LeetCode】896. Monotonic Array || 這一刻,意識到了自己的成長。題目: 給一個陣列,判斷內容是不是遞增或遞減
Thumbnail
avatar
2022-04-22
【LeetCode】19.Remove Nth Node From End of ListInput: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Thumbnail
avatar
2021-10-09
【LeetCode】876. Middle of the Linked ListInput: head = [1,2,3,4,5] Output: [3,4,5] 單看列表只是要找中間值,不過給定的資料結構不是陣列,而是鏈結串列。
Thumbnail
avatar
2021-10-09
【LeetCode】189. Rotate Array之前跳過的題目,回來補完成。 Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]
Thumbnail
avatar
2021-10-08
【LeetCode】557. Reverse Words in a String III今日題目: 把一行字內每個單字都反轉字元。 Input: s = "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"
Thumbnail
avatar
2021-10-08