↓快轉到主要內容
  1. LeetCode/

LeetCode 771: Jewels and Stones

·1 分鐘· ·
LeetCode Easy Hash-Table String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-09-06

  • 提交紀錄:Accepted → Runtime Error ×2 → Accepted

解題思路
#

把 jewels 轉成集合,stones 每個字元查一次是不是寶石,O(1) 查詢(Hash Table)。大小寫不同。

我的嘗試
#

中間兩次 RE 是用了舊版題目的參數名稱 J、S(NameError),改成 jewels、stones 就好了。

正確解法
#

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        jewel_set = set(jewels)
        return sum(s in jewel_set for s in stones)

複雜度
#

時間 O(n + m),空間 O(m)。

要特別避免的錯誤
#

  • 大小寫是不同的石頭。

面試口說整理
#

我把 jewels 放進集合,數 stones 裡有幾個字元在集合中,時間 O(n + m)。

相關文章

LeetCode 748: Shortest Completing Word
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 748 解題筆記:車牌只看字母並轉小寫計數,找出每個字母次數都夠的最短單字,同長度取最前面的
LeetCode 599: Minimum Index Sum of Two Lists
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 599 解題筆記:把 list1 的字串對應到 index,掃 list2 時算兩邊 index 的和,留下和最小的全部字串
LeetCode 290: Word Pattern
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 290 解題筆記:pattern 的字元和單字要一對一對應,用兩個方向的 dict 或比較 set 大小
LeetCode 383: Ransom Note
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 383 解題筆記:ransomNote 每個字元的需求數量都不能超過 magazine 的數量;Counter 相減為空就成立
LeetCode 387: First Unique Character in a String
·1 分鐘
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 解題筆記:先計數,再從左到右找第一個次數是 1 的字元
LeetCode 389: Find the Difference
·1 分鐘
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 解題筆記:t 比 s 多一個字元,把兩個字串的所有字元 XOR 起來,成對的抵消,剩下的就是多的那個